Why sizeof (* node) gives the size of the structure, not the size of the pointer
In the code below:
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 work? In the above case, * n2 boils down to giving the address where n2 points. n2 is still a dangling pointer in this case since we have no memory allocated and we do not point it to any valid address. How does it correctly size the structure?
source to share
You need to understand two things:
First, what type *n2
? The type n2
is a pointer to node
, so the type *n2
is node
.
Secondly, you are correct. n2
is a pointer pointer, it does not point to a valid location, but magic sizeof
is a compile-time operator (except when the operand is a C99 variable length array), sizeof(*n2)
evaluates the same as sizeof(node)
at compile time.
source to share
When you execute *n2
where n2
is defined as node* n2
, you are basically telling it to read the data at the address n2
as if it were of type node
.
It doesn't matter what is written on this 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.
source to share