Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program - Structure variable data packing and alignment

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?

like image 624
XOR Avatar asked Jan 20 '26 16:01

XOR


2 Answers

No, you are just printing the size of the pointers. It's not related to the internal member layout of structures.

like image 89
timrau Avatar answered Jan 23 '26 05:01

timrau


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));
like image 35
muXXmit2X Avatar answered Jan 23 '26 05:01

muXXmit2X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!