方大侠 发表于 2019-4-22 21:04:45

struct 为什么报错呀

struct学习过程中的问题

#include<stdio.h>

struct Date{
    int year;
    int month;
    int day;
};

struct Book{
    char title;
    char author;
    float price;
    struct Date date;
    char publisher;
};

int main(){
      struct Book book;
      book.date = {
                .year = 2017,
                .month = 11,
                .day = 11
         };

      printf("日期为%d-%d-%d\n",book.date.year,book.date.month,book.date.day);
}
输出结果:
test.c:19:14: error: expected expression(期望的表达???)
      book.date = {2017,11,11};
                  ^
1 error generated.

是结构体嵌套,不能部分初始化吗??我改成这样也是报错:
      struct Book book;
      book.date = {2017,11,11};

求大神指教。。。。。

人造人 发表于 2019-4-22 21:04:46

#include <stdio.h>

struct Date
{
        int year;
        int month;
        int day;
};

struct Book
{
        char title;
        char author;
        float price;
        struct Date date;
        char publisher;
};

int main(void)
{
      struct Book book = {.date = {.year = 2017, .month = 11, .day = 11}};
      printf("日期为 %d-%d-%d\n", book.date.year, book.date.month, book.date.day);
        return 0;
}
页: [1]
查看完整版本: struct 为什么报错呀