您的位置:首页 > 编程语言 > C语言/C++

C语言之struct和union分析

2018-03-27 23:23 477 查看
1.struct的小秘密
C语言中的struct可以看做变量的集合
struct的问题:
-空结构体占用多大内存?



相关测试代码:#include <stdio.h>

struct TS
{

};

int main()
{
struct TS ts1;
struct TS ts2;

printf("sizeof(struct TS) = %ld\n",sizeof(struct TS));
printf("sizeof(ts1) = %ld, &ts1 = %p\n",sizeof(ts1));
printf("sizeof(ts2) = %ld, &ts2 = %p\n",sizeof(ts2));

return 0;
}实验结果



以上结果是执行在gcc编译器,如果使用BCC编译器,则结果不同,此问题属于C语言中灰色地带

2.结构体与柔性数组
柔性数组即数组大小待定的数组
C语言中可以由结构体产生柔性数组
C语言中结构体的最后一个元素可以是大小未知的数组



柔性数组的用法



相关测试代码#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( NULL != sa )
{
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;
}实验结果



3.C语言中的union
C语言中的union在语法上与struct相似
union只分配最大成员的空间,所有成员共享这个空间



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;
}实验结果



说明:
喝水不忘挖井人,相关内容均转自狄泰软件学院,唐老师相关讲述
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: