C语言结构体中的类继承式用法?代码字段关联原理咨询
关于C语言柔性数组的疑问解答
问题代码
#include <stdlib.h> #include <stdint.h> #include <stdio.h> struct test_struct { uint8_t f; uint8_t weird[]; }; int main(void) { struct { struct test_struct tst; uint8_t weird[256]; } test_in = {}; printf("%u\n", test_in.weird[0]); // 0 test_in.tst.weird[0] = 1; printf("%u\n", test_in.weird[0]); // 1 return 0; }
核心疑问
- 这种用法在C语言中被称为什么?
- 该代码的运行原理是什么?为何修改
test_in.tst.weird[0]会改变test_in.weird[0]?两者看起来是独立字段。
1. 用法名称
结构体末尾的uint8_t weird[]是柔性数组成员(Flexible Array Member),属于C99标准引入的特性。
2. 运行原理
关键在于内存布局的连续性:
- 嵌套结构体
test_in的内存中,第一个成员struct test_struct tst仅占据1字节(来自uint8_t f),紧接着就是第二个成员uint8_t weird[256]的内存空间。 - 柔性数组成员本身不占用结构体的内存大小,它只是一个指针标记,指向结构体之后的连续内存区域。也就是说,
test_in.tst.weird直接指向tst后面的内存起始地址——也就是test_in.weird数组的首地址。 - 因此,
test_in.tst.weird[0]和test_in.weird[0]操作的是同一块内存单元,修改其中一个自然会影响另一个。
直白点说:柔性数组成员没有自己的独立存储,它“借用”了结构体后面紧跟的内存空间,这里刚好就是test_in.weird的内存,所以两者指向同一个位置。
内容的提问来源于stack exchange,提问作者k1r1t0
相关产品推荐
相关产品推荐

