GCC数组的struct编译怪异

时间:2009-08-29 18:27:06

标签: gcc

我很长时间没有使用过C语言。这是怎么回事?


wOCR.c:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
wOCR.c:9: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token

on this code:

struct wOCR_matchGrid {
  char character;
  int * data;
};

struct wOCR_matchGrid alphaMatch[26];

alphaMatch[0].character = 'A'; /*8*/
alphaMatch[0].data = {         /*9*/
                     0, 1, 0,
                     1, 0, 1,
                     1, 1, 1,
                     1, 0, 1   
                     };

3 个答案:

答案 0 :(得分:3)

首先,你应该在函数体内进行。然后,使用大括号的语法是非法的,因为您将它们分配给指针,而不是数组或结构。该语法也仅在初始化时有效,而不是在赋值期间有效。

代码可能正在使用复合文字,一些程序员删除了必要的类型名称:

void some_function(void) {
    struct wOCR_matchGrid alphaMatch[26];

    alphaMatch[0].character = 'A'; /*8*/
    alphaMatch[0].data = (int[]){         /*9*/
                         0, 1, 0,
                         1, 0, 1,
                         1, 1, 1,
                         1, 0, 1   
                         };

};

请注意我添加的括号int[]。这将告诉GCC在该函数调用的生命周期中创建一个未命名的数组,并将其地址分配给.data指针。在这种情况下,是一个演员,但是这个语法必须工作并创建一个数组复合文字。但是,这些复合文字是C99功能,并不适用于每个编译器。

答案 1 :(得分:1)

你应该在函数体内进行这些赋值。

答案 2 :(得分:0)

你可以这样做,但它太乱了地狱:

struct wOCR_matchGrid {
  char character;
  int data[12];
};

struct wOCR_matchGrid alphaMatch[26] = 
{
  {'A', {0, 1, 0,
           1, 0, 1,
           1, 1, 1,
           1, 0, 1}},
   {'B', {0, 1, 0,
           1, 0, 1,
           1, 1, 1,
           1, 0, 1}},
   /* etc */
};

请注意,在这种情况下,数据不能任意调整大小。