c语言中很有意思的union讲解

来源:互联网 发布:17报表数据分析实例 编辑:程序博客网 时间:2024/06/06 14:10

c语言中struct和union,太容易弄混淆了,看了下面的例子,就知道了,union和struct的区别:


union student {            char name[20];            char subject[20];            float percentage;};int main() {    union student record1;    union student record2;    // assigning values to record1 union variable       strcpy(record1.name, "Raju");       strcpy(record1.subject, "Maths");       record1.percentage = 86.50;       printf("Union record1 values example\n");       printf(" Name       : %s \n", record1.name);       printf(" Subject    : %s \n", record1.subject);       printf(" Percentage : %f \n\n", record1.percentage);    // assigning values to record2 union variable       printf("Union record2 values example\n");       strcpy(record2.name, "Mani");       printf(" Name       : %s \n", record2.name);       strcpy(record2.subject, "Physics");       printf(" Subject    : %s \n", record2.subject);       record2.percentage = 99.50;       printf(" Percentage : %f \n", record2.percentage);       return 0;}
输出为:

Name :Subject :Percentage : 86.500000;Union record2 values exampleName : ManiSubject : PhysicsPercentage : 99.500000

然后再来看看以下输出union和struct存储空间的大小:

#include<string.h>union student{    char name[20];    char subject[20];    float percentage;};struct teacher{    char name[20];    char subject[20];};typedef struct teacher Teacher;int main(){    union student st;    Teacher tc;    printf("%lu\n", sizeof(st));    printf("%lu\n", sizeof(tc));    return 0;

2030

可以看出,union分配的内存空间是20个字节,也就是union分配的内存是成员中占空间最大的成员的内存。而struct 就不同了,struct占的空间是所有成员占空间之和。


0 0
原创粉丝点击