C语言的struct与union怎么使用
导读:本文共1952字符,通常情况下阅读需要7分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 一、struct 的小秘密C语言中的 struct 可以看作变量的集合struct 的问题:空结构体占用多大内存?下面编写程序看一下吧:#include<stdio.h>structTS{};intmain(){structTSt1;structTSt2;printf("sizeof(structTS)=%d\n&q... ...
目录
(为您整理了一些要点),点击可以直达。一、struct 的小秘密
C语言中的 struct 可以看作变量的集合
struct 的问题:空结构体占用多大内存?下面编写程序看一下吧:
#include<stdio.h>structTS{};intmain(){structTSt1;structTSt2;printf("sizeof(structTS)=%d\n",sizeof(structTS));printf("sizeof(t1)=%d,&t1=%p\n",sizeof(t1),&t1);printf("sizeof(t2)=%d,&t2=%p\n",sizeof(t2),&t2);return0;}
下面为输出结果,可以看到在 gcc 编译器中空结构体的大小就为0。
二、结构体与柔性数组
柔性数组即数组大小待定的数组
C 语言中可以由结构体产生柔性数组
C 语言中结构体的最后一个元素可以是大小未知的数组
思考一下,下面的语句所占内存空间为多少呢,没错,就是 4。
SoftArray 中的 array 仅是一个待使用的标识符,不占用存储空间。
下面看一段柔型数组使用的代码:
#include<stdio.h>#include<malloc.h>structSoftArray{intlen;intarray[];};structSoftArray*create_soft_array(intsize){structSoftArray*ret=NULL;if(size>0){ret=(structSoftArray*)malloc(sizeof(structSoftArray)+sizeof(int)*size);ret->len=size;}returnret;}voiddelete_soft_array(structSoftArray*sa){free(sa);}voidfunc(structSoftArray*sa){inti=0;if(NULL!=sa){for(i=0;i<sa->len;i++){sa->array[i]=i+1;}}}intmain(){inti=0;structSoftArray*sa=create_soft_array(10);func(sa);for(i=0;i<sa->len;i++){printf("%d\n",sa->array[i]);}delete_soft_array(sa);return0;}
下面为输出结果:
虽然 array[ ] 数组在定义的时候没有指定大小,但是可以在后面使用 malloc 函数来指定大小。柔性数组的好处就是 func() 函数有一个指向柔性数组的合法指针就行,不用传递要处理的数组大小。
三、C语言中的 union
C语言中的 union 在语法上与 struct 相似
union 只分配最大成员的空间,所有成员共享这个空间
如下:
union 的使用受系统大小端的影响
如下,就是定义的字面量常数 i 在大小端的存储位置:
小端模式下地址值存储低位数据,大段模式下低地址存储高位数据。
下面编写程序来判断一下系统的大小端:
#include<stdio.h>intsystem_mode(){unionSM{inti;charc;};unionSMsm;sm.i=1;returnsm.c;}intmain(){printf("SystemMode:%d\n",system_mode());return0;}
下面为输出结果:
所以说我的电脑系统是小端
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
C语言的struct与union怎么使用的详细内容,希望对您有所帮助,信息来源于网络。