gpt4 book ai didi

C++ 返回数组并显示它

转载 作者:行者123 更新时间:2023-11-30 00:49:59 25 4
gpt4 key购买 nike

我想问一下,为什么这段代码不起作用...

int* funkce(){
int array[] = {1,2,3,4,5};
return(array);
}

int main(){

int* pp = funkce();
int* ppk = pp+5;

for (int *i = pp; i!=ppk; i++){
cout << (*i) << endl;
}

system("PAUSE");
return(0);
}

这段代码显示:

1
16989655
4651388
- // -
253936048

所以 poniter 超出了数组...但是怎么可能,这个在 Main 中带有数组的代码是可以的?

int main(){

int a[] = {1,2,3,4,5};
int* pp = a;
int* ppk = pp+5;

for (int *i = pp; i!=ppk; i++){
cout << (*i) << endl;
}
system("PAUSE");
return(0);
}

此代码显示:

1
2
3
4
5

你能给我解释一下,为什么第一个不起作用?谢谢!

最佳答案

当函数结束时,您将返回一个指向超出范围的临时指针。如果你想让一个函数返回一个数组,你需要执行以下操作之一:

std::array<int, 5> func() {
// stack-allocated
std::array<int, 5> a = {1, 2, 3, 4, 5};
return a;
}

std::vector<int> func() {
// heap-allocated
std::vector<int> a = {1, 2, 3, 4, 5};
return a;
}

int* func() {
// heap-allocated, you have to remember to delete it
int* a = new int[5]{1, 2, 3, 4, 5};
return a;
}

等有更多选择,但这应该会给您一个良好的开端。

关于C++ 返回数组并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26539374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com