使用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

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/266729.html

(0)
上一篇 2022年6月7日
下一篇 2022年6月7日

相关推荐

发表回复

登录后才能评论