Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the sizeof() function works for Structures in C?

Tags:

c

struct

The Structure is defined as follows

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

In Main Function, I called Sizeof the structure.

sizeof(struct Sample)

I've heard the return value of sizeof on structures could be incorrect. If this is the case, what should I do to get the right value?

like image 247
Karai Avatar asked Jan 04 '12 14:01

Karai


People also ask

How does sizeof struct work?

The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.

How does the sizeof function work in C?

It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

What is sizeof () in C with example?

The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in ​the computer's memory. A computer's memory is a collection of byte-addressable chunks.


1 Answers

It does return a reliable value - just not always the value you expect.

In Sample structure, you are assuming a 1 byte char and 4 byte int, but you do not get a result of "5" .

Because the structure is padded so that elements start on their natural boundaries. you are more likely to get a result of "8".

Wiki explains this pretty well: http://en.wikipedia.org/wiki/Sizeof - at "Structure Padding", near the bottom.

like image 155
karthik Avatar answered Nov 02 '22 16:11

karthik