I am new to the C language and just learned about structs and pointers.
My question is related to the offsetof
macro I recently saw. I know how it works and the logic behind that.
In the <stddef.h>
file the definition is as follows:
#define offsetof(type,member) ((unsigned long) &(((type*)0)->member))
My question is, if I have a struct as shown below:
struct test {
int field1:
int field2:
};
struct test var;
Why cannot I directly get the address of field2
as:
char * p = (char *)&var;
char *addressofField2 = p + sizeof(int);
Rather than writing something like this
field2Offset = offsetof (struct test, field2);
and then adding offset value to var's starting address?
Is there any difference? Is using offsetof
more efficient?
offsetof
and the like. You will not need it for normal programming, but only advanced features a beginner will very likely mess up. - Nop offence, but a very well meant warning! – Selfexcited