结构的尺寸如何与不同的数据类型而变化 [英] how size of a structure varies with different data types
问题描述
我使用Linux 32位操作系统,
和GCC编译器。
I am using Linux 32 bit os, and GCC compiler.
我尝试了三种不同类型的结构。
在第一个结构我已经定义只有一个字符
变量。这个结构的大小是1这是正确的。
I tried with three different type of structure.
in the first structure i have defined only one char
variable. size of this structure is 1 that is correct.
在第二结构中我已经定义只有一个 INT
变量。这里的结构尺寸显示4,这也是正确的。
in the second structure i have defined only one int
variable. here size of the structure is showing 4 that is also correct.
但在第三结构时,我定义了一个字符
和一个 INT
这意味着总规模应该是5,却是露出8输出谁能请解释结构是如何分配的?
but in the third structure when i defined one char
and one int
that means total size should be 5, but the output it is showing 8. Can anyone please explain how a structure is assigned?
typedef struct struct_size_tag
{
char c;
//int i;
}struct_size;
int main()
{
printf("Size of structure:%d\n",sizeof(struct_size));
return 0;
}
输出:结构的大小:1
typedef struct struct_size_tag
{
//char c;
int i;
}struct_size;
int main()
{
printf("Size of structure:%d\n",sizeof(struct_size));
return 0;
}
输出:结构尺寸:4
typedef struct struct_size_tag
{
char c;
int i;
}struct_size;
int main()
{
printf("Size of structure:%d\n",sizeof(struct_size));
return 0;
}
输出:
推荐答案
在大小的差别是由于对齐。编译器可以自由选择填充字节,使一个结构的总大小不一定其各元素的总和。
The difference in size is due to alignment. The compiler is free to choose padding bytes, which make the total size of a structure not necessarily the sum of its individual elements.
如果一个结构的填充是不希望的,因为它可能具有与某些硬件要求(或其他原因)接口,编译器通常支持包装结构,因此在填充被禁用。
If the padding of a structure is undesired, because it might have to interface with some hardware requirement (or other reasons), compilers usually support packing structures, so the padding is disabled.
这篇关于结构的尺寸如何与不同的数据类型而变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!