1、 struct的小秘密
空结构体占用的内存为0,不占用空间,空结构体所创建的变量也不占用空间
#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:Clion编译器
sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0x0093FF30
sizeof(t2) = 0, &t2 = 0x0093FF30
结果2:GCC编译器
sizeof(struct TS) = 0
sizeof(t1) = 0, &t1 = 0x7ffd7c56
sizeof(t2) = 0, &t2 = 0x7ffd7c57
结果3:VC编译器和BCC
error C2016: C 要求一个结构或联合至少有一个成员
可见不同编译器对空结构体的处理不同,一般认为是不允许空结构体存在,也没什么用,都有道理,
2、结构体与柔性数组(可变长数组)
3、柔性数组的用法
在申请大小空间时 一定要最后将数组的大小长度信息保存给len;
柔性数组 可以动态创建数组的大小;
#include <stdio.h>
#include <malloc.h>
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( 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);
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
4、C语言中的union
5、union的注意事项
#include <stdio.h>
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
小端模式