Re: pointer addition and structs

From: Severian (severian_at_chlamydia-is-not-a-flower.com)
Date: 12/16/04


Date: Thu, 16 Dec 2004 01:01:26 GMT

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