第10课-struct和union分析

18次阅读

共计 1454 个字符,预计需要花费 4 分钟才能阅读完成。

·C 语言中的 struct 可以看做变量的集合
不同类型的变量放在一起同时使用

例子 10-1:

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\n", sizeof(t1));
printf("sizeof(t1) = %d\n", sizeof(t2));
return 0;

}
输出结果:
error;代码中不允许出现空结构体

空结构体占用的内存为 0;

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

例子 10-1-1:

include “stdio.h”

struct soft_array
{

int len;
int array[];

};
int main()
{

printf("sizeof(struct soft_array) = %d\n", sizeof(struct soft_array));
return 0;

}
输出结果:
sizeof(struct soft_array) = 4

int array[]在代码中不占用内存,只是一个标识。

柔性数组使用分析例子 10-2:

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 (sa != NULL)
{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]);
}

}
输出结果:
1
2
3
4
5
6
7
8
9
10

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

·union 的使用受系统大小端的影响

小端模式:占用系统的低位
大端模式:占用系统的高位

判断系统的大小端 例子 10-3.c

include”stdio.h”

int system_mode()
{

typedef union 
{
    int a;
    char b;
}TS;
TS sm;
sm.a = 1;
return sm.b;

}
int main()
{

printf("system_mode:%d\n", system_mode());
return 0;

}
输出结果:
system_mode:1

小结:
·struct 中的每个数据成员都有独立的空间
·struct 可以通过最后的数组标识符产生柔性数组
·union 中的所有数据成员共享同一个存储空间
·union 是使用会受到系统大小端的影响

正文完
 0