struct和union分析
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;
}
输出结果为:
在gcc编译器中,空结构体大小为0
2、结构体与柔性数组
- 柔性数组即大小待定的数组
- C语言中可以由结构体产生柔性数组
- C语言中结构体的最后一个元素可以是大小未知的数组
柔性数组的用法
代码实践:
#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;
}
输出结果为:
3、union与struct的区别
#include <stdio.h>
struct my_struct
{
int a;
int b;
int c;
};
union my_union
{
int a;
int b;
int c;
};
int main(void)
{
printf("sizeof(struct my_struct) = %d\n",sizeof(struct my_struct));
printf("sizeof(union my_union) = %d\n",sizeof(union my_union));
return 0;
}
输出结果为:
4、用union来判断大小端
#include <stdio.h>
int system_mode()
{
union SM
{
int i;
char c;
};
union SM sm;
sm.i = 1;
return sm.c;
}
int main()
{
if(system_mode() == 1)
{
printf("little\n");
}
else
{
printf("big\n");
}
return 0;
}