0

The int size is 4 byte and when running this program, getting output as 16.
May I know the reason why the output is 16?

#include <stdio.h>

typedef struct list {
    int data;
    struct list *next;
} list;

int main()
{
    printf( "%d\n", sizeof(list) );
    return 0;
}
H.S.
  • 11,654
  • 2
  • 15
  • 32
Mukesh Bharsakle
  • 403
  • 1
  • 4
  • 17
  • 3
    Because padding paired with pointer size being equal to 8 on your machine. For sure there exist a duplicate of this question – Fureeish Nov 17 '18 at 01:40

1 Answers1

1

The type of each member of the structure usually has a default alignment, meaning that it will, unless otherwise requested by the programmer, be aligned on a pre-determined boundary.

As you mentioned that the size of int is 4 and size of pointer on your system architecture will be 8. Hence, to align the next pointer of structure list the compiler must be padding the structure with 4 bytes.

Some compilers supports the warning flag -Wpadded, which generates helpful warnings about structure padding, and one of them is gcc compiler. I have added couple of printf in your code to make the things clear:

#include <stdio.h>

typedef struct list {
    int data;
    struct list *next;
} list;

int main()
{
    list l;
    printf( "Size of struct list member data: %zu\n", sizeof(l.data) );
    printf( "Size of struct list member next: %zu\n", sizeof(l.next) );
    printf( "Size of struct list: %zu\n", sizeof(list) );
    return 0;
}

When compiling the code with -Wpadded flag, getting the warning message:

# gcc -Wpadded prg.c
p.c:5:18: warning: padding struct 'struct list' with 4 bytes to align 'next' [-Wpadded]
    struct list *next;
                 ^
1 warning generated.

The padding warning message from compiler is self explanatory.
Following is the output when running it:

#./a.out
Size of struct list member data: 4
Size of struct list member next: 8
Size of struct list: 16

Also, the type of the result of sizeof operator is size_t. You should use %zu format specifier instead of %d.

H.S.
  • 11,654
  • 2
  • 15
  • 32