【问题标题】:Structure within structure and function in CC中的结构和函数中的结构
【发布时间】:2014-02-25 07:30:31
【问题描述】:

我一直在做读取数据和创建特定结构的任务。 在一个结构(其本身包含另一个结构)中,日食显示“字段'出生'具有不完整的类型”。 我在网上搜索过,但似乎有一些特定的错误。 (这里是简化版的代码)

typedef struct{
    int birthday_day;
    int birthday_month;
    int birthday_year;
} birthday;

typedef struct{
    int id;
    char name[20];
    struct birthday birth;

}user;

user usser[100];
int i;

for (i=0;i<100;i++){
    fscanf(input, "%s %i %i %i %i", usser[i].id,  
           usser[i].name, usser[i].birth.birthday_day, usser[i].birth.birhday_month,
           usser[i].birth.birthday_year
};

【问题讨论】:

  • 和不同参数的序列。 scanf clan 需要一个指向参数的指针。 (例如&amp;usser[i].id
  • BLUEPIXY,谢谢。不过,我注意到只有在尝试启动该程序后

标签: c function structure


【解决方案1】:
typedef struct _birthday{
    int birthday_day;
    int birthday_month;
    int birthday_year;
} birthday;

typedef struct{
    int id;
    char name[20];
    struct _birthday birth;

}user;

typedef struct{
    int id;
    char name[20];
    birthday birth;

}user;

在您的示例中,“生日”是一种不需要关键字“struct”的新类型。这就是你得到错误的原因。您可以使用此类型或为结构命名,并将其与关键字 struct 一起使用。

【讨论】:

  • 谢谢!它有帮助!一旦获得足够的积分,就会投票赞成这个答案
  • 避免名称以下划线开头。使用 typedef struct birthday { … } birthday; 是完全安全和理智的,因为结构标签与 typedef 名称位于不同的命名空间中。您也可以使用typedef struct { … birthday birth; } user; 或使用struct user { … birthday birth; } user; 添加标签。
  • 我添加了前导下划线以显示差异,但我为什么要完全避免它们?
猜你喜欢
  • 2012-02-27
  • 2013-10-15
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多