Re: C Offsetof




<mihirtr@xxxxxxxxx> wrote in message news:1188575456.336130.313000@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi,
I have following structures and union

typedef struct
{
int a[100];
int b;
char *c;

}TEST_1;
typedef struct
{
int a[100];
char c[100];

}TEST_2;


union Member
{
TEST_1 test_1;
TEST_2 test_2;
};

typedef enum{
START_ID_0 = 0x2000,
START_ID_1,
START_ID_2,
START_ID_3,
START_ID_4
}SomeIdd;

typedef struct BufferTag
{
SomeId *id;
union Member *mem;
}Buffer;



In my program somehow I get pointer to "mem" in struct "Buffer". Now I
want to get value stored in "id". Is there a way. I read at multiple
places that I can use offsetof but when I try it gives by Segmentation
fault. Can you experts check this and let me know.
FOllowing is what I am doing.

#define GetMemFromBuf (out,source) \
(out) = (Buffer *) \
((char *) (source) - (offsetof(Buffer, mem)))

Following is that way I am accessing it.
Buffer *myBuff;
GetMemFromBuf (myBuff, (void *)myMem);
printf("ID = %d",(*myBuff->id));

Are you sure you get a pointer to mem, and not the value of mem itself?
Ie a union Member **, not a union Member * ?

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

.



Relevant Pages

  • Re: C Offsetof
    ... I have following structures and union ... int a; ... union Member *mem; ...
    (comp.lang.c)
  • Re: C Offsetof
    ... I have following structures and union ... int a; ... GetMemFromBuf (myBuff, (void *)myMem); ...
    (comp.lang.c)
  • Re: Is this valid program
    ... int main ... >pointer declared inside union. ...
    (comp.lang.c)
  • C Offsetof
    ... int a; ... char c; ... union Member *mem; ...
    (comp.lang.c)
  • Re: passing a unions field to a function
    ... Think of your union as an object. ... typedef struct X; ... void testFn(X x) ... You wouldn't expect to be able to pass an int to testFn, ...
    (comp.lang.c)