[英]C++ return pointer to dynamically allocated array
我正在閱讀這篇文章[函數返回指向int數組的指針],並學習返回pointer to int
的pointer to an array of int
和pointer to an array of int
之間的區別。
我在總結時遇到了幾個問題。 首先,看一下這段代碼(保持簡單):
函數test
和test2
返回pointer to int
的pointer to an array of int
和pointer to an array of int
int* test(size_t &sz) {
int *out = new int[5];
sz = 5;
return out;
}
int (*test2())[3] {
static int out[] = {1, 2, 3};
return &out;
}
如何更改test2
以使用動態數組(非靜態)? 是否可以通過數組大小作為參考或以某種方式傳遞?
主要功能如下所示。 代碼會編譯。
int main() {
size_t sz;
int *array = test(sz);
for (size_t i = 0; i != sz; ++i) {
array[i] = 10;
cout << *(array + i) << " ";
}
cout << endl;
delete[] array;
int (*array2)[3] = test2();
for (size_t i = 0; i != 3; ++i) {
cout << (*array2)[i] << " ";
}
}
結果
10 10 10 10 10
1 2 3
test2
不返回指向單個int
的指針,而是返回3元素int
數組的指針。 我鼓勵您嘗試使用精美的https://cdecl.org/網站,輸入int (*test2())[3]
然后自己看看。
您可能試圖返回new int[3]
,但失敗了。 這是因為new[]
返回指向單個int
(動態分配的數組的第一個元素)的指針,並且指向單個int
的指針不會自動轉換為指向多個int
的整個數組的指針。
如何更改
test2
以使用動態數組(非靜態)?
從技術上嚴格來說,像這樣:
int (*test2())[3] {
return reinterpret_cast<int(*)[3]>(new int[3] { 1, 2, 3 }); // horrible code
}
是否可以通過數組大小作為參考或以某種方式傳遞?
在test2
的情況下,數組的大小是類型的一部分,因此在編譯時固定。 您不能在運行時通過傳遞引用來更改類型。
現在,認真。
沒有想到的人會像這樣編寫代碼。 new[]
已經是一種非常糟糕的語言功能,使用額外的指針,引用和C語法特質進行額外的混淆處理並不能使其變得更好。 這是C ++, 使用std::vector
:
#include <iostream>
#include <vector>
std::vector<int> test() {
return { 1, 2, 3 };
}
int main() {
for (auto num : test()) {
std::cout << num << " ";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.