Leo Messi
Leo Messi

Reputation: 822

Offsetof used in Linux

I was going through how offset of a particular variable is found in a given structure.

I tried the following program .

struct info{
char a;
int b;
char c;
int d;
};

struct info myinfo;

int main(int argc, char **argv)
{
struct info *ptr = &myinfo;
unsigned int offset;

offset = (unsigned int) &((struct info *) 0)->d;
printf("Offset = %d\n",offset);

return 0;
}

I just wanted to know how the line offset = (unsigned int) &((struct info *) 0)->d works. I am confused because of dereferencing of 0.

Upvotes: 3

Views: 1292

Answers (2)

Richard Pennington
Richard Pennington

Reputation: 19965

You're not actually dereferencing 0. You're adding zero and the offset of the member, since you're taking the address of the expression. That is, if off is the offset of the member, you're doing

0 + off

not

*(0 + off)

so you never actually do a memory access.

Upvotes: 1

Damon
Damon

Reputation: 70126

It does not really dereference 0, although it looks like it. It really takes the address of some member if it was dereferenced at address 0, hypothetically.

This is a kind of dirty hack (plus, some nasty macro stuff), but it gets you what you're interested in (the offset of the member in the struct).

A more "correct" way of doing the same thing would be to generate a valid object, take its address, and take the address of the member, then subtract these. Doing the same with a null pointer is not all pretty, but works without creating an object and subtracting anything.

Upvotes: 5

Related Questions