【问题标题】:How to typedef structs in C in a non-standard way [closed]如何以非标准方式在 C 中键入定义结构 [关闭]
【发布时间】:2019-10-28 07:40:35
【问题描述】:

我在以非标准方式在 C 中定义结构时遇到问题。

我正在编写自己的内核。

struct Time {
    int sec;
    int min;
    int hour;
    int monthDay;
    int month;
    // Year count from 1900
    int year;
    // Week day <0; 6>; 0 - sunday...6 - saturday
    int weekDay;
    // Year day is counted from 0
    int yearDay;
    // If > 0 then there is summer time, if 0 then there is standard time,
    // if < 0 then there isn't info about time
    int timeZone;
};

typedef struct Time struct tm;     // Doesn't work :(((

我这里有一个编译错误。我想以两种方式定义 struct Time 变量:

  • struct Time a;
  • struct tm b;

我希望能够在tm b; 之前编写结构体,因为我想将类型 tm 标记为结构体而不是简单的原始类型。

【问题讨论】:

  • 你为什么不想用标准的方式来做呢?
  • 你真正想做什么?您需要解决的实际问题是什么?请花一些时间阅读有关how to ask good questions 和this question checklist 以及有关the XY problem 的信息(因为您的问题是一个)。
  • 如果你做typedef struct Time tm,那么你可以声明一个像tm b;。你为什么不想要那个?
  • 您知道标准C结构tm吗?为什么要更换它?同样,您需要通过“重载”标准tm 结构来解决真正的问题是什么?
  • 说实话,你说你想用struct tm是因为你想用struct tm。这真的不是什么理由,你还没有告诉我们为什么你想要它,或者应该解决什么问题(如果有)。我们只能得出结论,除了固执之外,你并没有真正的理由,也没有什么具体的问题需要解决。

标签: c struct typedef


【解决方案1】:

您尝试做的事情在很多方面都很奇怪。我看不到一个好的用例,但既然你问我会提供一个解决方案。但我会强烈不鼓励这样做。

#define tm Time

struct Time {
    int sec;
};

struct Time a;
struct tm b;

用常规的 typedef 解决这个问题是不可能的。

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2013-02-18
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多