使用联合类型共享内存

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

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

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

相关推荐

发表回复

登录后才能评论