·C语言中的struct能够看作变量的集合
不一样类型的变量放在一块儿同时使用数组
例子10-1:spa
struct Ts
{
};
int main()
{code
struct Ts t1; struct Ts t2; printf("sizeof(struct Ts) = %d\n", sizeof(struct Ts)); printf("sizeof(t1) = %d\n", sizeof(t1)); printf("sizeof(t1) = %d\n", sizeof(t2)); return 0;
}
输出结果:
error;代码中不容许出现空结构体blog
空结构体占用的内存为0;内存
结构体与柔性数组
·柔性数组即数组大小待定的数组
·C语言中能够由结构体产生柔性数组
·C语言中结构体的最后一个元素能够是大小未知的数组it
例子10-1-1:io
struct soft_array
{class
int len; int array[];
};
int main()
{变量
printf("sizeof(struct soft_array) = %d\n", sizeof(struct soft_array)); return 0;
}
输出结果:
sizeof(struct soft_array) = 4语法
int array[]在代码中不占用内存,只是一个标识。
柔性数组使用分析例子10-2:
struct SoftArray
{
int len; int array[];
};
struct SoftArray* create_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 = create_soft_array(10); func(sa); for (i = 0; i < sa->len; i++) { printf("%d\n", sa->array[i]); }
}
输出结果:
1
2
3
4
5
6
7
8
9
10
C语言中的union
·C语言中的union在语法上与struct类似
·union只分配最大成员的空间,全部成员共享这个空间
·union的使用受系统大小端的影响
小端模式:占用系统的低位
大端模式:占用系统的高位
判断系统的大小端 例子10-3.c
int system_mode()
{
typedef union { int a; char b; }TS; TS sm; sm.a = 1; return sm.b;
}
int main()
{
printf("system_mode:%d\n", system_mode()); return 0;
}
输出结果:
system_mode:1
小结:·struct中的每一个数据成员都有独立的空间·struct能够经过最后的数组标识符产生柔性数组·union中的全部数据成员共享同一个存储空间·union是使用会受到系统大小端的影响