vikasm
vikasm

Reputation: 79

Why does sizeof(*node) give the size of the structure and not size of the pointer

In the below code:

typedef struct{int data1; int data2} node;
node n1;
node* n2;

sizeof(n1) returns 8 // size of the struct node
sizeof(n2) returns 4 // since n2 is a pointer it returns the size of the pointer
sizeof(*n2) returns 8 // HOW DOES THIS WORK ?

How does sizeof actually work ? In the above case *n2 boils down to providing the address of where n2 is pointing. n2 in this case is still a dangling pointer as we have neither allocated memory nor are we pointing it to some valid address. How does it give the size of the structure correctly ?

Upvotes: 3

Views: 432

Answers (3)

GreenAsJade
GreenAsJade

Reputation: 14685

Basically, you can read *n2 as "the thing that n2 is pointing at".

The thing that n2 is pointing at is a node, and the sizeof a node is 8. Simple as that... it doesn't matter whether it's been allocated or not: the type of the thing that n2 is pointing at is a node, and the size of a node is 8.

Upvotes: 2

penelope
penelope

Reputation: 8418

When you do *n2, where n2 is defined as node* n2 you are basically telling it to read the data at the address n2 as if it had the type node.

It does not matter what is written on that address. Consider adding these lines to your example:

void *n3 = n2; // copies the address, but no information about the data there
int *n4 = (int *)n3; // again, copies the address

sizeof(*n4) returns sizeof(int)

So basically, to summarize, if you have:

X* a;
sizeof(a); // will always return 4, the size of a pointer
sizeof(*a); // will always return sizeof(X), no matter if the address is set.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122403

You need to understand two things:

First, what's the type of *n2? The type of n2 is a pointer to node, so the type of *n2 is node.

Second, you are right n2 is a danging pointer, it doesn't point to a valid place, but the magic of sizeof is, it's a compile time operator (except when the operand is a C99 variable length array), sizeof(*n2) is evaluated as the same as sizeof(node) in compilation time.

Upvotes: 13

Related Questions