[sdiy] Pointers in C

Magnus Danielson magnus at rubidium.dyndns.org
Sat Dec 31 17:23:00 CET 2011


On 12/31/2011 12:42 PM, Paul Maddox wrote:
> All,
>
>    Pointers have always confused me, though I'm getting better slowly.
>
>    But I have a question, if I have a pointer to an unsigned long int (32bits) and I want to access it as four unsigned chars, do I just read a char and increase the pointer? for example;
>
> 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;
>
>    or am I nuts?

Hi nuts,

since you declared a int pointer the pointer arithmetic is in the size 
of that. In this case you use int and assuming that the int has size of 
16 bits, then you will increment in 2 byte steps with each ++.

The code you wrote is equalent to

char * my_ptr;
my_ptr = (char *)my_unsigned_long_int_ptr;
unsigned char FirstByte = *my_ptr;
my_ptr = my_ptr + 2;
unsigned char SecondByte = *my_ptr
my_ptr = my_ptr + 2;

What you want is to convert your pointer to a pointer of the size you 
want, char, and then you can access it sequentially as above. Thus:

char *my_ptr = (char *)my_unsigned_long_int_ptr;

Further, if you indeed have a long int variable which you want to pick 
the bytes from, then you would do this:

char *my_ptr = (char *)&my_unsigned_long_int;

Where the & operator gives you the address of the variable after it of 
the type of that variable, in this case you get a long int * from this, 
which is then type-converted in the (char *) expression.

Pointer arithmetic in C is a bit confusing at first, but it is kind of 
neat. Another way to write the same thing would be

unsigned char FirstByte = my_ptr[0];
unsigned char SecondByte = my_ptr[1];
...

which is the same as

unsigned char FirstByte = *(my_ptr+0);
unsigned char SecondByte = *(my_ptr+1);
...

Cheers,
Magnus



More information about the Synth-diy mailing list