Reputation: 314
What will be the output of the program on a 32-bit machine (using GCC)? Explain.
#include<stdio.h>
int main() {
struct node {
int data;
struct node *link;
};
struct node *p, *q;
p = (struct node *) malloc(sizeof(struct node));
q = (struct node *) malloc(sizeof(struct node));
printf("%d, %d\n", sizeof(p), sizeof(q));
return 0;
}
The output shows
4, 4.
Is the above program related to structure member alignment padding and data packing?
Upvotes: 3
Views: 175
Reputation: 134286
Point 1 Use %zu
format specifier to print the output of sizeof
of type size_t
.
Point 2 Note the type of p
, it is struct node *
, same as q
.
So, essentially, sizeof(p)
and sizeof(q)
are exactly same as sizeof(struct node *)
, which, on your platform are 32 bit wide. As you're not considering a variable here, so the alignment and padding for the structure and members are neither relevant nor involved in this case.
That said, please see why not to cast the return value of malloc()
and family in C
.
Upvotes: 2
Reputation: 2765
On a 32-bit system the stored addresses are always 32 bits big. If you're printing the size of a pointer you're basically just printing the size of the address it points to (32 Bit -> 4 Byte)
.
If you want to know the size of the struct do something like this:
struct node p;
struct node q = {4, &p};
printf("%zu, %zu\n", sizeof(p), sizeof(q));
Upvotes: 2
Reputation: 23058
No, you are just printing the size of the pointers. It's not related to the internal member layout of structures.
Upvotes: 3
Reputation: 4118
No, it is not related to the structure member alignment padding and data packing.
Since it is a 32-bit machine the size of any pointer will be 4
bytes. Since p and q are of type struct node *
i.e. pointer to struct node
the result prints size of pointers p
and q
.
Upvotes: 0