C语言结构体成员占用空间总和与实例大小不符问题咨询
结构体额外字节的原因解析
代码示例
typedef struct { string city; int temp; } avg_temp; avg_temp temps[NUM_CITIES]; void sort_cities(void); int main(void) { temps[0].city = "Austin"; temps[0].temp = 97; temps[1].city = "Boston"; temps[1].temp = 82; temps[2].city = "Chicago"; temps[2].temp = 85; temps[3].city = "Denver"; temps[3].temp = 90; temps[4].city = "Las Vegas"; temps[4].temp = 105; temps[5].city = "Los Angeles"; temps[5].temp = 82; temps[6].city = "Miami"; temps[6].temp = 97; temps[7].city = "New York"; temps[7].temp = 85; temps[8].city = "Phoenix"; temps[8].temp = 107; temps[9].city = "San Francisco"; temps[9].temp = 66; }
问题描述
经计算,
sizeof(temps)=160,sizeof(temps[0])=16,sizeof(temps[0].city)=8,sizeof(temps[0].temp)=4。由于city和temp总共占用12字节,请问temps[0]中额外的4字节是什么?
解答
这是**结构体内存对齐(Padding)**导致的,具体细节如下:
- 你的运行环境是64位系统,
string本质是char*指针,占8字节;int类型占4字节。C语言中,结构体的整体对齐规则是:以成员中对齐要求最高的类型大小为边界,这里指针的对齐要求是8字节,所以整个结构体的大小必须是8的整数倍。 - 结构体里
city占8字节,temp占4字节,加起来12字节,不满足8的整数倍要求。编译器会自动在temp后面填充4字节,让整个结构体的大小凑到16字节(8×2),以此符合对齐规则。 - 内存对齐是编译器的优化手段:CPU访问内存时,按对齐后的边界读取数据会更高效,避免跨内存块读取带来的性能开销。
另外补充:标准C语言中并没有string类型,你这里的string应该是char*的别名(比如通过typedef char* string;定义),这也是它占8字节的原因。
内容的提问来源于stack exchange,提问作者DCR
相关产品推荐
相关产品推荐

