标签:基础上 size 引入 数据 提高 free 不同类 行操作 占用
一、struct关键字与柔性数组
1 struct softarry 2 { 3 int len; 4 int arry[]; 5 }; 6 7 int main() 8 { 9 printf("%d\n",sizeof(struct softarry)); 10 return 0; 11 } 12 13 输出结果为4(默认在32位机器上)
编译器不为arry分配内存空间,因为也不知道arry有多大,只是用来当作一个标识符,以便以后可以通过这个标识符来访问其中的内容。
1 #include<stdio.h> 2 #include<malloc.h> 3 typedef struct softarry 4 { 5 int len; 6 int arry; 7 } my_softarry; 8 9 my_softarry* creat_softarry(int size) 10 { 11 my_softarry *ret=NULL; 12 if(size>0) 13 { 14 ret=(my_softarry*)malloc(sizeof(my_softarry)+sizeof(int)*size); 15 ret->len=size; 16 } 17 return ret; 18 } 19 20 void delete_softarry(my_softarry **sa) 21 { 22 free(*sa); 23 *sa=NULL; 24 } 25 26 /*给柔性数组每个元素赋值*/ 27 void func(my_softarry *sa) 28 { 29 int i=0; 30 if(NULL!=sa) 31 { 32 for(i=0;i<sa->len;i++) 33 { 34 sa->arry[i]=i+1; 35 } 36 } 37 } 38 39 int main() 40 { 41 int i=0; 42 my_softarry*sa=creat_softarry(10);//初始化结构指针 43 fun(sa);//使用柔性数组 44 for(i=0;i<sa->len;i++) 45 { 46 printf("%d",sa->arry[i]); 47 delete_softarry(&sa);//释放操作柔性数组的结构体指针 48 return 0; 49 } 50 }
二、union关键字
1 struct A 2 { 3 int i; 4 char c; 5 } 6 union B 7 { 8 int i; 9 char c; 10 } 11 12 printf("%d%d",sizeof(struct A),sizeof(union B)); 13 14 输出结果为:54
因此union只分配最大成员空间,且所有成员共享这一空间。即共用同一个内存首地址,同时共用体的成员都可以对这份空间进行操作,操作也是共同生效。
2.union系统大小端问题
1 union C 2 { 3 int i; 4 char c; 5 } 6 unio C c; 7 c.i==1; 8 printf("%d",c.c); 9 此时输出的值应该为多少
1 #includ <stdio.h> 2 /*检测处理器大小端,大端模式返回0,小段模式返回1*/ 3 int checkcpu() 4 { 5 union w 6 { 7 int a; 8 char b; 9 } c; 10 c.a=1; 11 return(c.b==1); 12 } 13 14 int main() 15 { 16 printf("%d",checkcpu()); 17 return 0; 18 }
三、enum枚举类型关键字
1 enum color 2 { 3 RED; 4 BLUE=2; 5 GREEN; 6 }; 7 8 其中RED=0;BLUE=2;GREEN=3
enum变量的类型实际上是int类型
标签:基础上 size 引入 数据 提高 free 不同类 行操作 占用
原文地址:https://www.cnblogs.com/southcyy/p/10172486.html