How to find the offset of a variable in a structure
Answers
Answered by
0
Answer:
Step-by-step explanation:
struct a foo;
printf("offset of k is %d\n", (char *)&foo.y.k - (char *)&foo);
printf("offset of i is %d\n", (char *)&foo.x.i - (char *)&foo);
foo.x.i refers to the field i in the struct x in the struct foo. &foo.x.i gives you the address of the field foo.x.i. Similarly, &foo.y.k gives you the address of foo.y.k; &foo gives you the address of the struct foo.
Subtracting the address of foo from the address of foo.x.i gives you the offset from foo to foo.x.i.
As Gangadhar says, you can use the offsetof() macro rather than the pointer arithmetic I gave. But it's good to understand the pointer arithmetic first.
Hope it helps you....
Similar questions
India Languages,
6 months ago
English,
6 months ago
Social Sciences,
6 months ago
Math,
11 months ago
Chemistry,
11 months ago
Geography,
1 year ago
Social Sciences,
1 year ago
Biology,
1 year ago