C++ functions returning arrays(C++ 函数返回数组)
问题描述
我对 C++ 有点陌生.我习惯用 Java 编程.这个特殊的问题给我带来了很大的问题,因为 C++ 在处理数组时不像 Java.在 C++ 中,数组只是指针.
I am sort of new to C++. I am used to programming in Java. This particular problem is causing me great issues, because C++ is not acting like Java when it is dealing with Arrays. In C++, arrays are just pointers.
但是为什么会出现这样的代码:
But why does this code:
#include <iostream>
#define SIZE 3
using namespace std;
void printArray(int*, int);
int * getArray();
int ctr = 0;
int main() {
int * array = getArray();
cout << endl << "Verifying 2" << endl;
for (ctr = 0; ctr < SIZE; ctr++)
cout << array[ctr] << endl;
printArray(array, SIZE);
return 0;
}
int * getArray() {
int a[] = {1, 2, 3};
cout << endl << "Verifying 1" << endl;
for (ctr = 0; ctr < SIZE; ctr++)
cout << a[ctr] << endl;
return a;
}
void printArray(int array[], int sizer) {
cout << endl << "Verifying 3" << endl;
int ctr = 0;
for (ctr = 0; ctr < sizer; ctr++) {
cout << array[ctr] << endl;
}
}
为验证 2 和验证 3 打印任意值.也许这与数组真正作为指针处理的方式有关.
print out arbitrary values for verify 2 and verify 3. Perhaps this has something to do with the way arrays are really handled as pointers.
推荐答案
因为你的数组是栈分配的.从 Java 迁移到 C++,您必须非常小心对象的生命周期.在 Java 中,所有内容都是堆分配的,并且在没有对它的引用时进行垃圾收集.
Because your array is stack allocated. Moving from Java to C++, you have to be very careful about the lifetime of objects. In Java, everything is heap allocated and is garbage collected when no references to it remain.
然而,在这里,您定义了一个堆栈分配的数组 a,当您退出函数 getArray 时该数组被销毁.这是向量优于普通数组的(许多)原因之一——它们为您处理分配和解除分配.
Here however, you define a stack allocated array a, which is destroyed when you exit the function getArray. This is one of the (many) reasons vectors are preferred to plain arrays - they handle allocation and deallocation for you.
#include <vector>
std::vector<int> getArray()
{
std::vector<int> a = {1, 2, 3};
return a;
}
这篇关于C++ 函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 函数返回数组
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
