2008-12-23 72 views
8

如果我創建一個文件:無法轉換(*)[]以**

TEST.CPP:

void f(double **a) { 

} 

int main() { 
    double var[4][2]; 
    f(var); 
} 

然後運行: G ++ TEST.CPP -o測試

我得到

test.cpp: In function `int main()': 
test.cpp:8: error: cannot convert `double (*)[2]' to `double**' for argument `1' 
to `void f(double**)' 

爲什麼我不能這樣做?

是不是雙var [4] [2]是做雙** var然後分配內存相同?

回答

17

C++ strings: [] vs. *

看那遊覽:多維數組它描述瞭如何通過多維數組函數作爲參數。基本上,您想將您的代碼更改爲:

// same as void f(double (*a)[2]) { 
void f(double a[][2]) { 

} 

int main() { 
    // note. this is not a pointer to a pointer, 
    // but an array of arrays (4 arrays of type double[2]) 
    double var[4][2]; 

    // trying to pass it by value will pass a pointer to its 
    // first element 
    f(var); 
} 

除被調用函數以外的所有維度都必須知道。否則,編制數組索引時,編譯器將無法計算到陣列中值的正確距離(a [1]距離[0]爲sizeof(double[2])字節)。

您似乎想要在不知道尺寸大小的情況下接受陣列。您可以使用模板此:

template<std::size_t N> 
void f(double a[][N]) { 
    // N == 2 for us 
} 

int main() { 
    double var[4][2]; 
    f(var); 
} 

編譯器將(實例),該模板與功能使用的各個N值的副本,自動推斷正確的N.

+0

謝謝,我喜歡你給我的鏈接,因爲我可以從那裏獲得更深入的見解。還有你給我的模板例子。 double a [] [2]正是我在我的特定程序中所需要的。 – Ezequiel 2008-12-24 18:05:35

0

的問題是雙**是指向指針的指針。你的'f'函數想要將指針的地址傳遞給double。如果你調用f(var),那麼你認爲指針在哪裏?它不存在。

這將工作:

double *tmp = (double *) var; 
f (&tmp); 

而且,它會努力改變f的定義:

void f (double a[4][2]) { } 

現在˚F採用指向你有類型的數組。那可行。

+1

沒有不行。你的f函數需要double **,而不是指向數組的指針。而且你的演員陣容也是錯誤的。將double [4] [2]轉換爲double *並期望這樣工作是不正確的。出於上述原因。請不要這樣做。 – 2008-12-24 02:21:01

相關問題