c语言联合数据类型,使用联合类型共享内存

union类型允许通过许多不同的变量共享内存。以下语句声明了一个由三个变量共享的联合:

union U_example

{

float decval;

int *pnum;

double my_value;

} u1;

这是一个使用联合的例子。

#include

typedef union UDate UDate;

typedef struct Date Date;

typedef struct MixedDate MixedDate;

typedef struct NumericDate NumericDate;

void print_date(const Date* date); // Prototype

enum Date_Format{numeric, text, mixed}; // Date formats

struct MixedDate{

char *day;

char *date;

int year;

};

struct NumericDate{

int day;

int month;

int year;

};

union UDate{

char *date_str;

MixedDate day_date;

NumericDate nDate;

};

struct Date

{

enum Date_Format format;

UDate date;

};

int main(void){

NumericDate yesterday = { 11, 11, 2012};

MixedDate today = {"Monday", "12th November", 2012};

char tomorrow[] = "Tues 13th Nov 2012";

// Create Date object with a numeric date

UDate udate = {tomorrow};

Date the_date;

the_date.date = udate;

the_date.format = text;

print_date(&the_date);

// Create Date object with a text date

the_date.date.nDate = yesterday;

the_date.format = numeric;

print_date(&the_date);

// Create Date object with a mixed date

the_date.date.day_date = today;

the_date.format = mixed;

print_date(&the_date);

return 0;

}

void print_date(const Date* date){

switch(date->format) {

case numeric:

printf("The date is %d/%d/%d.\n", date->date.nDate.day,date->date.nDate.month,date->date.nDate.year);

break;

case text:

printf("The date is %s.\n", date->date.date_str);

break;

case mixed:

printf("The date is %s %s %d.\n", date->date.day_date.day,date->date.day_date.date,date->date.day_date.year);

break;

default:

printf("Invalid date format.\n");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值