[英]Returning a pointer to an array C++
我有一個函數需要返回一個指向數組的指針:
int * count()
{
static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
return &myInt[10];
}
在我的主要函數中,我想顯示該數組中的一個整數,例如此處的索引3
int main(int argc, const char * argv[])
{
int myInt2[10] = *count();
std::cout << myInt2[3] << "\n\n";
return 0;
}
但是,這給了我錯誤:“數組初始化器必須是初始化器列表”
如何在我的主函數中創建一個數組,該數組使用指針獲取與指針處的數組相同的元素?
您的代碼中的一些問題:
1)您需要在count中返回一個指向數組開頭的指針:
return &myInt[0];
要么
return myInt; //should suffice.
然后,當您初始化myInt2時:
int* myInt2 = count();
您還可以將一個數組復制到另一個數組中:
int myInt2[10];
std::copy(count(), count()+10, myInt2);
注意復制將使用與第一個數組不同的內存創建第二個數組。
您不需要指針,引用就可以了。
int (&count())[10]
{
static int myInt[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
return myInt;
}
int main(int argc, const char * argv[])
{
int (&myInt2)[10] = count();
std::cout << myInt2[3] << "\n\n";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.