How does the sizeof () function work for Structures in C?

The structure is defined as follows

typedef struct Sample { int test; char strtest; } Sample; 

In the main function, I called the Sizeof structure.

 sizeof(struct Sample) 

I heard that the return value of sizeof on structures may be wrong. If so, what should I do to get the correct value?

+6
source share
4 answers

It returns a valid value - simply not always the expected value.

In the Sample structure, you accept 1 char byte and 4 int bytes, but you do not get the result "5".

Since the structure is complemented so that the elements begin with their natural boundaries. you will most likely get the result "8".

The wiki explains this pretty well: http://en.wikipedia.org/wiki/Sizeof - in the Layout Structure section, below.

+22
source

Sizeof is not a function; this is an operator. This result is always correct, but sometimes unexpected, due to the addition or belief that it is a determinant of the size of the magic array.

As an operator, brackets are not needed if they act in a variable.

  int foo; printf("%zu\n", sizeof foo); 

is completely legal.

+1
source

sizeof with a structural type works like any other type: the result of the statement is the size of the type in bytes. The size of the structure type is the same as the size of the object of this structure type.

The sizeof structure object may be larger than the size of the various elements of the structure types due to filling.

There may be a padding of an unspecified number of bytes after each structure element, and padding is taken into account in the size of the structure type (or object of the structure type).

To print the size of the structure type, use the z transform specifier in the printf format printf :

 printf("%zu\n", sizeof (struct my_structure_type)); 
+1
source
0
source

Source: https://habr.com/ru/post/905106/


All Articles