2012-11-30 141 views
7

我對C++相當陌生,最近遇到了這個問題。通過引用傳遞數組?

此代碼顯然會工作:

void setvalues(int *c, int *d) 
{ 
    (*c) = 1; 
    (*d) = 2; 
} 
int main() 
{ 
    int a, b; 
    setvalues(&a, &b); 
    std::cout << a << b; 
} 

那麼,爲什麼這個返回一個錯誤? VISUAL C++ 2010錯誤:

C2664: 'setvalues' : cannot convert parameter 1 from 'int (*)[2]' to 'int *[]'

void setvalues(int *c[2], int *d[2]) 
{ 
    (*c[1]) = 1; 
    (*d[1]) = 2; 
} 
int main() 
{ 
    int a[2], b[2]; 
    setvalues(&a, &b); 
    std::cout << a[1] << b[1]; 
} 

有何不同之處指向數組?我四處搜尋,但沒有運氣。

+0

[CDECL(http://cdecl.ridiculousfish.com/?q=int+*c%5B2%5D)是你的朋友。 –

回答

6

類型int *a[2]裝置陣列的2個指針int,但與定義int a[2]表達&a裝置指針爲2的數組int。兩者都是不同的類型,它們之間沒有轉換。由於弗拉德已經提到,爲您提供需要加括號的正確類型:

void setvalues(int (*c)[2]) 

或者你可以使用實際引用在C++:

void setvalues(int (&c)[2]) 

在你不需要的後一種情況使用或取消對它的引用地址的運營商setvalue函數內部:

int a[2]; 
setvalues(a); // this is a reference to the array 

寫的代碼更簡單的方法是使用typedef

typedef int twoints[2]; 
void setvalue(toints& c); 
int main() { 
    twoints a; // this is int a[2]; 
    setvalue(a); 
} 
+0

我明白了,謝謝。我認爲它也是一樣的字符串數組呢? – NoToast

+0

@ user1867129:它取決於* string *的含義,但是對於所有類型,語法是一致的,如果要使用指向數組的指針,則必須使用倒置圓括號(倒置的意思是圓括號'int(* a)[2]'實際上將*之外的所有內容*括號括起來:* a是指向在parens之外描述的類型的指針*) –

3

它需要是void setvalues(int (&c)[2], int (&d)[2])通過引用傳遞。而來電者必須是setvalues(a, b);。否則,你最多隻能通過指針傳遞指針。

+0

感謝您的回答! – NoToast

2

這是你如何解決它:

void setvalues(int c[], int d[]) 
{ 
    c[1] = 1; 
    d[1] = 2; 
} 
int main() 
{ 
    int a[2],b[2]; 
    setvalues(a, b); 
    std::cout<<a[1]<<b[1]; 
} 

在聲明數組是這樣的:int a[2],b[2];,然後ab已經指針到這些陣列的開始。

而當你做a[0],那就是當你實際上以某個偏移量來訪問數組以訪問數組中的元素時。 a[1],例如,是相同的*(a+1)

參考:http://www.cplusplus.com/doc/tutorial/arrays/

+1

這不完全正確,因爲它與傳遞指針相同。該陣列的長度是多少?它在編譯期間執行?沒有.. – 2012-11-30 18:28:55