[sdiy] Pointers in C
jayv at synth.net
Sat Dec 31 17:36:22 CET 2011
Best thing is to use a union though - this will let you set up some aliases to individual parts of the word without arithmetic and pointer mess. It is definitely good to understand the increment/decrement rules that the compiler follows for type sizes, but beyond that: use a union. It's clean and relatively painless.
On Dec 31, 2011, at 17:23, Magnus Danielson <magnus at rubidium.dyndns.org> wrote:
> On 12/31/2011 12:42 PM, Paul Maddox wrote:
>> 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;
>> unsigned char SecondByte = *my_ptr;
>> unsigned char ThirdByte = *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;
> unsigned char SecondByte = my_ptr;
> which is the same as
> unsigned char FirstByte = *(my_ptr+0);
> unsigned char SecondByte = *(my_ptr+1);
> Synth-diy mailing list
> Synth-diy at synth-diy.org
More information about the Synth-diy