Re: pointer addition and structs

From: Drew Myers (drew.nospam.myers_at_esrd.com)
Date: 12/16/04


Date: Thu, 16 Dec 2004 11:26:40 -0600

Thanks.

Drew

"Severian" <severian@chlamydia-is-not-a-flower.com> wrote in message
news:a3n1s0tc140q9ui1chmtsul16440ksrcmd@4ax.com...
> On Wed, 15 Dec 2004 18:27:51 -0600, "Drew Myers"
> <drew.nospam.myers@esrd.com> wrote:
>
>>Is there a way using pointer addition to access struct members?
>>
>>Say:
>>
>>struct foo{
>> char str[16];
>> int i;
>>}
>>
>>How would I get to i?
>
> struct foo x;
>
> unsigned char *pfoo = (BYTE *)&x;
> unsigned char *p = pfoo + offsetof(foo, i);
> int *pi = (int *)p;
>
> or more succintly...
>
> int *pi = (int *)(((unsigned char *)&x) + offsetof(foo, i));
>
> For this type of access, make sure you do all your math using pointers
> to char or unsigned char.
>
> This is rarely needed, but quite useful when necessary.
>
> --
> Sev



Relevant Pages