如果我可以已知大小的數組傳遞:在C++中返回一個已知大小的數組?
void fn(int(*intArray)[4])
{
(*intArray)[0] = 7;
}
爲什麼不能返回一個:
int intArray[4] = {0};
int(*)[4] fn()
{
return &intArray;
}
在此, 「)」 中的 「(*)」 生成「語法錯誤:)「。
如果我可以已知大小的數組傳遞:在C++中返回一個已知大小的數組?
void fn(int(*intArray)[4])
{
(*intArray)[0] = 7;
}
爲什麼不能返回一個:
int intArray[4] = {0};
int(*)[4] fn()
{
return &intArray;
}
在此, 「)」 中的 「(*)」 生成「語法錯誤:)「。
的[4]
進入函數名後,就好像它會在變量名後的變量定義:
int (*fn())[4]
{
return &intArray;
}
因爲這是很晦澀的語法,容易被如果沒有任何特別的理由說明它必須是數組指針,那麼我會建議將數組作爲簡單的int*
返回。
你也可以用一個typedef簡化函數定義:
typedef int intarray_t[4];
intarray_t* fn() { ... }
您可以返回int**
或者void *。兩者都有關於數組大小的信息。 – 2010-06-09 12:14:25
Its not allowed to return arrays from functions, but there are workarounds。
例如,下面的代碼:
int fn()[4] {
...
沒有得到通過各種在線編譯器接受;我試了一下在科莫在線編譯器,它被認爲是編譯器的最標準以下情況之一,甚至在輕鬆模式,它說:
error: function returning array is not allowed
另一個海報建議返回int**
;這會起作用,但要非常小心,你返回堆分配的內存,而不是堆棧分配。
你正在傳遞一個指向已知大小數組的指針。在C++中,引用可能會更好,因爲它將像數組一樣行爲,而不必對其進行解引用。 – 2010-06-09 12:16:36