[英]Having trouble using an array that is returned by a function in C++
我有一個函數,可以在數組中生成值並返回指向該數組的指針。 這是MWE代碼:
int *f(size_t s)
{
int *ret=new int[s];
for(size_t a=0;a<s;a++)
{
ret[a]=a;
cout << ret[a] << endl;
}
return ret;
}
請注意,我有一個cout
線在該陣列被正確填充for循環來證明自己。
現在,這是我的問題。 我找不到使用返回數組的正確方法。 這是我一直在做的事情:
int main (void)
{
int ary_siz = 10;
int ary[ary_siz];
*ary = *f(ary_siz);
cout << ary[0] << endl;
cout << ary[2] << endl;
cout << ary[3] << endl;
}
ary
的第一個元素似乎是正確的。 其他( ary[1]
, ary[2]
...)則不是。 誰能告訴我我在做什么錯?
int main (void)
{
int ary_siz = 10;
int *ary = f(ary_siz);
cout << ary[0] << endl;
cout << ary[2] << endl;
cout << ary[3] << endl;
delete [] ary;
}
分配
*ary = *f(ary_siz);
復制單個元素。 采用
int main (void)
{
int ary_siz = 10;
int *ary = f(ary_siz);
delete[] ary;
}
修復內存泄漏
您在函數中分配一個數組,然后將其第一個元素分配給堆棧分配的數組的第一個元素,而不僅僅是使用返回的數組。
您應該這樣做:
int main (void)
{
int ary_siz = 10;
int *ary;
ary = f(ary_siz);
cout << ary[0] << endl;
cout << ary[2] << endl;
cout << ary[3] << endl;
delete[] ary // don't forget to release the memory
return 0; // You should return something in the main function
}
此外,在C ++中,應盡可能使用向量而不是“裸機”數組。
這個怎么樣?
int *ary = f(ary_siz);
您可以像在提示中一樣使用[]運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.