FengYue20 发表于 2022-5-21 18:50:30

怎么将结构体嵌套代码写在下面

请问我想将结构体中次结构体代码写到主结构体代码下面,但是使用extern又会报错,请问如何才能实现???
代码如下:
#include <stdio.h>

struct Book
{
      char title;//书名
      float price;//价格
      struct Date date;//日期
};
struct Date
{
      int year;//年
      int month;//月
      int day;//日
};

int main(void)
{
      struct Book book;
      scanf("%d",&book.date.year);
      printf("%d\n",book.date.year);

      return 0;
}
~

wp231957 发表于 2022-5-21 19:14:05

肯定要写在上面啊,为啥要放下面

傻眼貓咪 发表于 2022-5-21 21:19:55

#include <stdio.h>

struct Date // <------------ 注意这里
{
    int year, month, day;
};

struct Book
{
    char title;
    float price;
    struct Date date; // <------------ 注意这里,这里实例结构体 Date,所以 Date 必须在 Book 上面
};

int main(void)
{
    struct Book book;
    scanf("%d", &book.date.year);
    printf("%d\n", book.date.year);
    return 0;
}
页: [1]
查看完整版本: 怎么将结构体嵌套代码写在下面