【问题标题】:expected ';' at end of declaration list c when i have one already预期的 ';'在声明列表 c 的末尾,当我已经有一个时
【发布时间】:2016-01-13 14:06:32
【问题描述】:

我试图在一个名为 bread 的结构中声明和数组,但它一直给我预期的错误 ';'当我已经有一个时,在声明列表的末尾。

typedef struct
{
   char bread[9][35] = {
   "1. 9-Grain Wheat", 
   "2. 9-Grain Honey Oat", 
   "3. Italian", 
   "4. Italian Herbs & Cheese",
   "5. Flatbread (not baked in restaurant)", 
   "6. Cheese Bread", 
   "7. Hearty Italian", 
   "8. Parmesan Oregano", 
   "9. Roasted Garlic" };        
} subway;

这是结构所在的头文件的内容

【问题讨论】:

  • 请贴出整个代码,这个sn-p自己无法重现问题。 Post a minimal example that reproduces the problem, or a MCVE.
  • 你为什么要这么做?为什么是结构?
  • C 中的初始化器必须在对象的定义之后,而不是在类型定义中。无论如何,如果字符串是常量,最好使用const char *bread[]
  • "5. Flatbread (not baked in restaurant)" 对于char bread[9][35] 来说太大了。它的大小为 39 个字符(38 + 终止 nul 字符)

标签: c


【解决方案1】:

您无法初始化 typedef 中的结构。当您定义该类型的变量时,您必须这样做:

typedef struct
{
   char bread[9][50];   // the longest string is 38 characters, so the second dimension 
                        // should be at least 39 (38 plus the null terminating byte)
                        // we'll round up to 50 to leave space for expansion
} subway;

subway s = {{
   "1. 9-Grain Wheat",
   "2. 9-Grain Honey Oat",
   "3. Italian",
   "4. Italian Herbs & Cheese",
   "5. Flatbread (not baked in restaurant)",
   "6. Cheese Bread",
   "7. Hearty Italian",
   "8. Parmesan Oregano",
   "9. Roasted Garlic"
}};

【讨论】:

    【解决方案2】:

    typedef 是一个类型定义,它不是一个变量声明。初始化一个类型没有任何意义。

    你应该这样做:

    typedef struct
    {
       char bread[9][LARGE_ENOUGH];
    } subway_t;
    
    ...
    
    subway_t sub = { /* initialization */ };
    

    【讨论】:

    • 绝对不需要把类型名改成subway_t
    • @iharob 个人喜好。你可以叫它metro 我关心的是:)
    【解决方案3】:

    您的字符串太长 - 打开编译器警告(最高级别)

    'bread' : array bounds overflow
    

    试试

    char bread[9][40] = {
    

    改为。

    更新问题

    无需将单个数组放入结构中。如果确实需要在 typedef 内部使用这个,只使用char bread[9][40];,并在 typedef 外部初始化数组:

    typedef struct
    {
       char bread[9][40];
    } subway;
    
    subway mySubway = { /* initialize strings here */ };
    

    【讨论】:

    • 虽然这似乎是真的,但这不是 OP 所要求的。你能把它作为评论吗?
    【解决方案4】:

    你的初始化是错误的:你试图用 (char *) [] 来初始化一个 char [][]。 你应该使用 strncpy 来初始化这样一个数组

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    相关资源
    最近更新 更多