C++返回数组并显示它
C++ returning array and display it
我想问一下,为什么这段代码不起作用。。。
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
所以小马出了阵。。。但是怎么可能,这个在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;
}
等等。有更多的选择,但这应该会给你一个良好的开端。
永远不要返回本地变量。如果是对变量的指针/引用,则返回时会释放/重新使用内存。
使用悬挂引用是未定义的行为,会产生不可预测的后果。
返回一个对象、指向堆分配内存的指针,或保存到调用方提供的缓冲区中。
相关文章:
- 显示数组中的学生 ID 和最高分
- 我编写了一个程序来显示数组的内容,但它显示的是它的地址
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 使用指针显示数组的值
- 我无法显示包含整数最大值的索引. 但我可以显示数组中整数的最高值
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 使用增量/减少操作员在C 中显示数组的奇怪结果
- 将25个甚至整数存储到一个名为intlist的整数阵列中,然后在屏幕上显示数组,并在屏幕上显示名为fivintegers
- 显示数组的问题.一切都放在一个单独的行中,但不放入单独的列中
- strlen 显示数组元素的数量错误
- 我的函数不会用" "替换".",也不会按预期显示数组
- 以C++为单位乘以并显示数组的值
- 找不到标识符,尝试在 C++ 中显示数组值
- 如何显示数组名称中的名称
- 在列表小部件 Qt C++中显示数组内容
- c++将.txt文件中的字符串添加到字符串数组中,并显示数组的值
- C++如何将数组传递给函数,然后调用它来显示数组的值
- 从函数更新(覆盖)和显示数组
- 在单独的数据中显示数组数据
- 仅显示数组文本文件中的第一个字母