struct , union 关键字分析
来源:互联网 发布:上古卷轴5战斗优化mod 编辑:程序博客网 时间:2024/06/05 20:48
结构体struct的 定义
三种写法:
//第一种typedef struct _tag_student{ int ID; char* name;}Student;...Student s1;
//第二种struct _tag_student{ int ID; char* name;};...struct _tag_student s2;
//第三种typedef struct _tag_student Student;struct _tag_student{ int ID; char* name;};...Student s3;
struct 关键字 分析
空结构体的大小分析:
空结构体的大小的定义是C语言的灰色地带,不同的编译器对于空结构体的大小有不同的定义,
例如下面的一段程序:
不同的编译器有不同的编译结果:
- d1和d2的大小都为0字节,起始地址相同。
- d1和d2的大小都为1字节,起始地址不同。
使用结构体定义柔性数组:
柔性数组即数组大小待定的数组
C语言中结构体的最后一个元素可以是大小未知的数组
C语言中可以由结构体产生柔性数组
如下所示:
struct SoftArray{ int len; int Array[];};
举例1:结构体构建柔性数组:
#include <stdio.h>#include <malloc.h>typedef struct _soft_array{ int len; int array[];}SoftArray;int main(){ int i = 0; printf("%d\n", sizeof(SoftArray));//此时输出的结构体的大小为4字节,是len的大小 SoftArray* sa = (SoftArray*)malloc(sizeof(SoftArray) + sizeof(int) * 10); sa->len = 10; for(i=0; i<sa->len; i++) { sa->array[i] = i + 1; } for(i=0; i<sa->len; i++) { printf("%d\n", sa->array[i]); } free(sa); return 0;}
举例2:使用柔性数组存储斐波那契数组:
#include <stdio.h>#include <malloc.h>typedef struct _soft_array{ int len; int array[];}SoftArray;SoftArray* create_soft_array(int size){ SoftArray* ret = NULL; if( size > 0 ) { ret = (SoftArray*)malloc(sizeof(*ret) + sizeof(*(ret->array)) * size); ret->len = size; } return ret;}void fac(SoftArray* sa){ int i = 0; if( NULL != sa ) { if( 1 == sa->len ) { sa->array[0] = 1; } else { sa->array[0] = 1; sa->array[1] = 1; for(i=2; i<sa->len; i++) { sa->array[i] = sa->array[i-1] + sa->array[i-2]; } } } }void delete_soft_array(SoftArray* sa){ free(sa);}int main(){ int i = 0; SoftArray* sa = create_soft_array(10); fac(sa); for(i=0; i<sa->len; i++) { printf("%d\n", sa->array[i]); } delete_soft_array(sa); return 0;}
union 关键字分析
struct中的每个域在内存中都独立分配空间
union只分配最大域的空间,所有域共享这个空间
上面例子中A的大小为12字节,B的大小为4字节。
union的使用受系统大小端的影响
大端模式下,低位数据存放在高地址处。
小端模式下,低位数据存放在低地址处。
在上面的例子中,union C占用了4个字节的空间,如果系统为大端模式,则输出的char c的内容为0;如果系统为小端模式,则输出的char c的内容为1.
举例:判断系统为大端还是小端:
#include <stdio.h>char chec_system(void){ union C { int i; char c; }cc; cc.i = 1; return 1 == cc.c;}int main(){ if (chec_system()) printf("系统为小端模式"); else printf("系统为大端模式"); return 0;}
0 0
- struct , union 关键字分析
- 《C关键字分析》之sizeof,enum、union和struct
- 专题一关键字的剖析----6.struct,union的分析
- struct和union分析
- struct和union分析
- struct,union分析
- struct和union分析
- C语言关键字--- struct union
- union 关键字的用法与struct
- 代码分析题(1):struct & union
- sizeof(struct)分析(包括union)
- union , struct
- Struct & Union
- struct union
- struct, union
- struct union
- struct union
- Struct&Union
- ==与equals
- 使用Maven自动部署Java Web应用到Tomcat服务器
- 二阶段提交,三阶段提交,Paxos
- Kylin Cube构建过程优化
- sql 事务
- struct , union 关键字分析
- ArrList、HashSet、HashMap 的遍历和区别
- SVN查看提交历史
- SpringMVC学习系列(3) 之 URL请求到Action的映射规则
- Gradle的大型项目常用库和版本管理
- open failed: ENOENT (No such file or directory)!
- numpy 学习笔记(1)
- Spring源码解析
- 概率图模型学习(3)——贝叶斯网与马尔科夫网的关联