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?

+3


source to share


4 answers


No, you are just printing the size of the pointers. It is not related to the internal structure of the structural elements.



+3


source


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));

      

+2


source


  • Point 1 Use a format specifier %zu

    to output sizeof

    type inference size_t

    .

  • Point 2 Note the type p

    , this struct node *

    is the same as q

    .

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

.

+2


source


No, it has nothing to do with complementing struct alignment and data packing.

Since this 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 the size of the pointers p

and q

.

0


source







All Articles