- C 语言中的 srtuct 能够看做变量的集合
struct 的问题 : 空结构体占用多大内存?编程
void code() { struct TS { }; printf("%d\n", sizof(struct TS)); }
#include <stdio.h> struct TS { }; int main() { struct TS t1; struct TS t2; printf("sizeof(struct TS) = %d\n", sizeof(struct TS)); printf("sizeof(t1) = %d\n", sizeof(t1), &t1); printf("sizeof(t2) = %d\n", sizeof(t1), &t2); return 0 }
输出:【GCC】 sizeof(struct TS) = 0 sizeof(t1) = 0 sizeof(t2) = 0
C 语言的灰色地带:不一样编译器有不一样的行为数组
- GCC 大小为 0
- BCC, VC 报错
struct SoftArray { int len; int array[]; // 当且仅看成为结构体的最后一个元素时能够使用 }; // ... struct SoftArray* sa = NULL; sa = (struct SoftArray*)malloc(sizeof(struct SoftArray) + sizeof(int) * 5)); sa->len = 5; printf("%d\n", sizeof(struct SoftArray)); // 4
#include <stdio.h> #include <malloc.h> struct SoftArray { int len; int array[]; }; struct SoftArray* creat_soft_array(int size) { struct SoftArray* ret = NULL; if( size > 0 ) { ret = (struct SoftArray*)malloc(sizeof(struct SoftArray) + sizeof(int) * size); ret->len = size; } return ret; } void delete_soft_array(struct SoftArray* sa) { free(sa); } void func(struct SoftArray* sa) { int i = 0; if( sa != NULL ) { for(i=0; i<sa->len; i++) { sa->array[i] = i + 1; } } } int main() { int i = 0; struct SoftArray* sa = creat_soft_array(10); func(sa); for(i=0; i<sa->len; i++) { printf("%d\n", sa->array[i]); } delete_soft_array(sa); return 0; }
输出: 1 2 3 4 5 6 7 8 9 10
- C 语言中的 union 在语法上与 struct 类似
- union 只分配最大成员的空间,全部成员共享这个空间
void code_1() { struct A { int a; int b; int c; } printf("%d\n", sizeof(struct A)); // 12 } void code_2() { union B { int a; int b; int c; } printf("%d\n", sizeof(union B)); // 4 }
union 的使用受系统大小端的影响spa
- 小端,低字节在低地址
- 大端,低字节在高地址
void code() { union C { int i; char c; }; union C c; c.i = 1; printf("%d\n", c.c); // ? }
int system_mode() { union SM { int i; char c; }; union SM sm; sm.i = 1; return sm.c; } int main() { printf("System Mode: %d\n", system_mode()); return 0; }
输出:低字节在低地址,小端 System Mode: 1
- strut 中的每一个数据成员有独立的存储空间
- strut 能够经过最后的数组标识符产生柔性数组
- union 中的全部数据成员共享一个存储空间
- union 的使用会受到系统大小端的一影响
以上内容参考狄泰软件学院系列课程,请你们保护原创!code