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
.