2015-01-05 63 views
-1

可能是一個非常簡單的問題,但我找不出原因。所有給定的代碼都在同一個文件中。不能返回靜態數組

這是陣列中的一個的定義。它是在每種方法之外定義的。

unsigned char KEY_40_COMPARE_VALUES[] = { 
85,102 
,119,134 
,147,158 
,165,169 
,169,165 
,158,147 
,134,119 
,102,85 
,67,50 
,35,22 
,11,4 
,0,0 
,4,11 
,22,35 
,50,67 
}; 

這是代碼:

unsigned char * getCompareValuesForIndex(char index) 
{ 
    if (index == 0) 
    { 
     return KEY_28_COMPARE_VALUES; 
    } 

    if (index == 1) 
    { 
     return KEY_30_COMPARE_VALUES; 
    } 

    if (index == 2) 
    { 
     return KEY_32_COMPARE_VALUES; 
    } 

    if (index == 3) 
    { 
     return KEY_33_COMPARE_VALUES; 
    } 

    if (index == 4) 
    { 
     return KEY_35_COMPARE_VALUES; 
    } 

    if (index == 5) 
    { 
     return KEY_37_COMPARE_VALUES; 
    } 

    if (index == 6) 
    { 
     return KEY_39_COMPARE_VALUES; 
    } 

    else 
    { 
     return KEY_40_COMPARE_VALUES; 
    } 
} 

這是編譯錯誤,我得到:

conflicting types for 'getCompareValuesForIndex' 
+0

你在哪裏調用這個函數'getCompareValuesForIndex'? – Gopi

+1

您也可以用查找表替換所有這些if語句。 – OldProgrammer

+0

你能介紹一下函數的定義嗎?還在項目中搜索單詞'getCompareValuesForIndex'檢查是否有其他定義/其他用途的名稱 –

回答

3

這樣的錯誤,通常當你做你的函數的調用提供之前發生一個原型,並在文件聲明之前。在這種情況下,編譯器假定

  • 任何參數的函數採用是int類型,並且
  • 該函數返回值的類型的int

本質上,函數看起來像這樣,以編譯器:

int getCompareValuesForIndex(int index) { // <<= What compiler thinks 
    ... 
} 

當編譯器看到實際聲明時,它發出錯誤。

要解決這個問題,無論是(1)提供提前調用的函數原型,或(2)移動定義爲早於您首次使用功能的。

注:帶着這個問題的出路,考慮優化功能,通過添加一個靜態數組,像這樣:

unsigned char *KEY_COMPARE_VALUES[] = { 
    KEY_28_COMPARE_VALUES 
, KEY_30_COMPARE_VALUES 
, KEY_32_COMPARE_VALUES 
, KEY_33_COMPARE_VALUES 
, KEY_35_COMPARE_VALUES 
, KEY_37_COMPARE_VALUES 
, KEY_39_COMPARE_VALUES 
}; 

現在你的函數可以寫成這樣:

unsigned char * getCompareValuesForIndex(char index) { 
    return (index >=0 && index < 7) ? KEY_COMPARE_VALUES[index] : KEY_40_COMPARE_VALUES; 
} 
+0

感謝您的建議。我會在時限後接受答案。 – Utku