注:博客中内容主要来自《狄泰软件学院》,博客仅当私人笔记使用。
测试环境:Ubuntu 10.10
GCC版本:4.4.5
一、struct的小秘密
1) C语言中的struct可以看作变量的集合
2) struct的问题
- 空结构体占用多大内存?
实例分析
空结构体的大小
10-1.c
#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, &t1 = %p\n", sizeof(t1), &t1);
printf("sizeof(t2) = %d, &t2 = %p\n", sizeof(t2), &t2);
return 0;
}
操作:
1) gcc 10-1.c -o 10-1.out编译正确,打印结果:
sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0xbf80c33e
sizeof(t2) = 0, &t2 = 0xbf80c33f
分析:
gcc下struct Ts空结构体大小为0。在栈上连续被分配空结构体t1和t2。
二、结构体与柔性数组
1) 柔性数组即数组大小待定的数组。
2) C语言中可以由结构体产生柔性数组。
3) C语言中结构体的最后一个元素可以是大小未知的数组。
三、结构体与柔性数组
1) 柔性数组的用法
struct SoftArray
{
int len;
int array[];
};
// ...
struct SoftArray* sa = NULL;
sa = (struct SoftArray*)malloc(sizeof(struct SoftArray) + sizeof(int)*5);
sa->len = 5;
实例分析
柔性数组使用分析
10-2.c
#include <stdio.h>
#include <malloc.h>
//1.定义柔性数组
struct SoftArray //结构体模板,存储在bss段
{
int len;
//int array[]; //修改第10行
};
//创造柔性数组,定义柔性数组长度,返回结构体
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( NULL != sa ) //判断数组是否为空,否则赋值无意义,白干活,浪费了
{
for(i=0; i<sa->len; i++)
{
sa->array[i] = i + 1;
}
}
}
int main()
{
int i = 0;
struct SoftArray* sa = create_soft_array(10);//创造一个长度为10的柔性数组
func(sa);
for(i=0; i<sa->len; i++)
{
printf("%d\n", sa->array[i]);
}
delete_soft_array(sa);
return 0;
}
操作:
1) gcc 10-2.c -o 10-2.out编译正确,打印结果:
1
2
3
4
5
6
7
8
9
10
四、C语言中的union
1) C语言中的union在语法上与struct相似
2) union只分配最大成员的空间,所有成员共享这个空间
五、union的注意事项
1) union的使用受系统大小端的影响
小端模式:就是低位字节排放在内存的低地址端,高位字节排放在内存的高地址端。
大端模式:就是高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。
编程实验
编程判断系统的大小端
10-3.c
#include <stdio.h>
int system_mode()
{
union SM
{
int i;
char c;
};
union SM sm;
sm.i = 1;
printf("sm = %p\n", &sm);
printf("sm.i = %p\n", &sm.i);
printf("sm.c = %p\n", &sm.c);
return sm.c;
}
int main()
{
printf("System Mode: %d\n", system_mode());
return 0;
}
操作:
1) gcc 10-3.c -o 10-3.out编译正确,打印结果:
sm = 0xbfa138ec
i = 0xbfa138ec
c = 0xbfa138ec
System Mode: 1
小端模式
分辨大小端设计思想:利用共享内存地址截断分辨大小端地址。int为4字节,char为1字节。
或者暴力强转:
int a = 0x11223344;
char b = *((char*)&a);
printf("b = %#x"); //0x11(大端) or 0x44(小端)
小结:
1) struct中的每个数据成员有独立的存储空间
2) struct可以通过最后的数据标识符产生柔性数组
3) union中的所有数据成员共享同一个存储空间
4) union的使用会受到系统大小端的影响