[sdiy] Pointers in C
Olivier Gillet
ol.gillet at gmail.com
Sat Dec 31 13:39:17 CET 2011
int *my_ptr = my_unsigned_long_int;unsigned char FirstByte =
*my_ptr;my_ptr++;unsigned char SecondByte = *my_ptr;my_ptr++;unsigned
char ThirdByte = *my_ptr;my_ptr++;unsigned char FourthByte = *my_ptr;
This won't work because pointer arithmetic always uses the size of the
underlying type. Here we are assuming that sizeof(int) = 32
Let's say my_unsigned_long_int is at address 0x1000
> int *my_ptr = &my_unsigned_long_int;
my_ptr will store address 0x1000 (I assume you forgot the &)
> unsigned char FirstByte = *my_ptr;
FirstByte will contain the 8 MSB of the 32-bit int at address 0x1000
(ie byte at 0x1000 or byte at 0x1003 depending on the endianness of
the platform).
> my_ptr++;
my_ptr will store address 0x1004 ; because my_ptr is an int pointer ;
and pointer arithmetic always uses the size of the interlying type (
To do what you want to do, you need to use an unsigned char pointer.
unsigned char* my_ptr = (unsigned char*)(&my_unsigned_long_int).
unsigned char FirstByte = *my_ptr;
my_ptr++;
...
The union is a simpler way of accessing individual bytes or words ;
though it is still endinanness dependent. The most portable way of
accessing individual bytes from words is still shifting and masking.
Olivier
More information about the Synth-diy
mailing list