使用联合类型共享内存

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

union U_example
{
  float decval;
  int *pnum;
  double my_value;
} u1;

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

#include <stdio.h>

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);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。