C - structural variable data packing and alignment
What will the program output be 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 displays
4, 4.
Is the above program related to padding alignment of structure members and packing data?
source to share
On a 32-bit system, stored addresses are always 32 bits. If you are printing the size of the pointer, you are basically just printing the size of the address that is pointing to (32 Bit -> 4 Byte)
.
If you want to know the size of a structure, do something like this:
struct node p;
struct node q = {4, &p};
printf("%zu, %zu\n", sizeof(p), sizeof(q));
source to share
-
Point 1 Use a format specifier
%zu
to outputsizeof
type inferencesize_t
. -
Point 2 Note the type
p
, thisstruct node *
is the same asq
.
So, essentially, sizeof(p)
and sizeof(q)
exactly the same as sizeof(struct node *)
, which on your platform are 32 bits wide. Since you are not considering a variable here, so alignment and padding for structure and elements are neither relevant nor involved in this case.
Here you go , see why not distinguish between return value malloc()
and families in C
.
source to share