[英]returning an int array
I have created the following program which is supposed to return an int array to the main function, which will then display it on the screen. 我创建了以下程序,该程序应该将int数组返回给main函数,然后将其显示在屏幕上。
#include <iostream.h>
int* returnArray(){
int* arr;
arr[0]=1;
arr[1]=2;
arr[2]=3;
return arr;
}
int main(){
int* res = returnArray();
for(int i=0; i<3; i++){
cout<<res[i]<<" ";
}
return 0;
}
And i was expecting it to print 我期待它能打印
1 2 3
1 2 3
but instead, it prints 3 someNumberWhichLooksLikeAPointer 0 但是,它打印3 someNumberWhichLooksLikeAPointer 0
Why is that? 这是为什么? what can i do to return an int array from my function?
我该怎么做才能从我的函数返回一个int数组? Thank you very much!
非常感谢你!
You forgot to allocate your array: 您忘记分配数组了:
int* arr = new int[3];
You also need to return it, and free the memory inside main
after you finish with the loop in order to avoid a memory leak: 您还需要返回它,并在完成循环后释放
main
内部的内存,以避免内存泄漏:
delete[] res;
Although this approach works, it is not ideal. 尽管此方法有效,但并不理想。 If you have an option of returning a container, say,
std::vector<int>
it would be a much better choice. 如果您可以选择返回容器,例如
std::vector<int>
那将是一个更好的选择。
If you must stay with plain arrays, another solution for filling an array inside an API is to pass it in, along with its size: 如果必须使用普通数组,则在API中填充数组的另一种解决方案是将数组及其大小传递进去:
void fillArray(int *arr, size_t s){
if (s > 0) arr[0]=1;
if (s > 1) arr[1]=2;
if (s > 2) arr[2]=3;
}
int main(){
int res[3];
fillArray(res, 3);
for(int i=0; i<3; i++){
cout<<res[i]<<" ";
}
return 0;
}
You have tagged the question with C++
. 您已使用
C++
标记了问题。 You Yous should consider to use the C++ solution: use a vector of int
您应该考虑使用C ++解决方案:使用
int
向量
#include <iostream>
#include <vector>
std::vector<int> returnArray(){
std::vector<int> arr(3);
arr[0]=1;
arr[1]=2;
arr[2]=3;
return arr;
}
int main(){
std::vector<int> res = returnArray();
for(int i=0; i<3; i++){
std::cout<<res[i]<<" ";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.