鱼C论坛

 找回密码
 立即注册
查看: 2219|回复: 1

[已解决]struct 为什么报错呀

[复制链接]
发表于 2019-4-22 21:04:45 | 显示全部楼层 |阅读模式
5鱼币
struct学习过程中的问题

  1. #include<stdio.h>
  2.   
  3. struct Date{
  4.     int year;
  5.     int month;
  6.     int day;
  7. };

  8. struct Book{
  9.     char title[128];
  10.     char author[40];
  11.     float price;
  12.     struct Date date;
  13.     char publisher[40];
  14. };

  15. int main(){
  16.         struct Book book;
  17.         book.date = {
  18.                 .year = 2017,
  19.                 .month = 11,
  20.                 .day = 11
  21.          };

  22.         printf("日期为%d-%d-%d\n",book.date.year,book.date.month,book.date.day);
  23. }
复制代码

输出结果:
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
  1. #include <stdio.h>
  2.   
  3. struct Date
  4. {
  5.         int year;
  6.         int month;
  7.         int day;
  8. };

  9. struct Book
  10. {
  11.         char title[128];
  12.         char author[40];
  13.         float price;
  14.         struct Date date;
  15.         char publisher[40];
  16. };

  17. int main(void)
  18. {
  19.         struct Book book = {.date = {.year = 2017, .month = 11, .day = 11}};
  20.         printf("日期为 %d-%d-%d\n", book.date.year, book.date.month, book.date.day);
  21.         return 0;
  22. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-4-22 21:04:46 | 显示全部楼层    本楼为最佳答案   
  1. #include <stdio.h>
  2.   
  3. struct Date
  4. {
  5.         int year;
  6.         int month;
  7.         int day;
  8. };

  9. struct Book
  10. {
  11.         char title[128];
  12.         char author[40];
  13.         float price;
  14.         struct Date date;
  15.         char publisher[40];
  16. };

  17. int main(void)
  18. {
  19.         struct Book book = {.date = {.year = 2017, .month = 11, .day = 11}};
  20.         printf("日期为 %d-%d-%d\n", book.date.year, book.date.month, book.date.day);
  21.         return 0;
  22. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-6 23:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表