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

妖精的绣舞 提交于 2020-02-03 05:16:07

问题


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?


回答1:


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.




回答2:


Sizeof is not a function; it is an operator. It's result is always correct, but sometimes unexpected, due to padding, or the belief that it is a magical array size determiner.

As an operator, the parentheses are not needed if acting in a variable.

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

is perfectly legal.




回答3:


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

The sizeof a structure object can be more than the size of the different elements of the structure types because of padding.

There can be padding of unspecified number of bytes after every structure member and the padding is taken into account in the size of the structure type (or of an object of the structure type)

To print the size of a structure type use the z conversion specifier in a printf format string:

printf("%zu\n", sizeof (struct my_structure_type));



回答4:


Here you can read a little bit more about that: http://somectips.wordpress.com/2012/01/05/what-is-the-size-of-struct/



来源:https://stackoverflow.com/questions/8728377/how-the-sizeof-function-works-for-structures-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!