编程学习网为您整理以下代码实例,主要实现:使用union在成员之间共享内存,希望可以帮到各位朋友。
结构体为每个成员保留单独的内存段,union
为其最大成员保留单个内存空间。使用关键字union
创建联合体。
以下代码为电话簿创建联合体定义。
union phoneBook {
char *name;
char *number;
char *address;
};
通过点(.
)运算符访问联合体成员。
#include <stdio.h>
union phoneBook {
char *name;
char *number;
char *address;
};
struct magazine {
char *name;
char *author;
int isbn;
};
int main()
{
union phoneBook aBook;
struct magazine aMagazine;
printf("\nUnion Details\n");
printf("Address for aBook.name: %p\n", &aBook.name);
printf("Address for aBook.number: %p\n", &aBook.number);
printf("Address for aBook.address: %p\n", &aBook.address);
printf("\nStructure Details\n");
printf("Address for aMagazine.name: %p\n", &aMagazine.name);
printf("Address for aMagazine.author: %p\n", &aMagazine.author);
printf("Address for aMagazine.isbn: %p\n", &aMagazine.isbn);
} //end main
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!