2009-08-29 47 views
0

我很久沒用過C了。這裏發生了什麼?GCC結構編譯器怪異數組

 

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 
        }; 
+2

你不能在函數之外放置任意C代碼。 – 2009-08-29 18:30:49

回答

1

你應該在函數體內部做這些賦值。

+0

DUH !!!! thnx lotz。我的C – woxorz 2009-08-29 18:36:51

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 */ 
}; 

注意,數據不能隨意在這種情況下,大小。

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功能,並不適用於每個編譯器。

+0

已經很硬了,當然,複合文字不適用於所有的編譯器(特別是不適用於MSVC!),但它們在GCC中工作,除非您告訴它不要使用「-std = c89」或某些類似的選項。 – 2009-08-29 19:17:47