问题描述
int** function()
{
int M[2][2] = {{1,2},{3,4}};
return (int **)M; //is this valid?
}
void anotherFn()
{
int **p = new int*[2];
for(int i = 0; i<2; i++) {
p[i] = new int[2];
}
p = function();
cout << p[0][0];
}
上面的代码已编译,但给出了运行时错误.因此,仅当将2D数组声明为双指针时,才能返回2D数组吗?或者是否可以通过某种方式将2D数组作为2D指针返回?
The above code compiled but gave runtime error. So, can I return a 2D array only if it was declared as double pointer or is there some way I can return an array as a 2D pointer?
推荐答案
您正在将2D数组表示为指向int的指针.那是个坏主意.更好的主意是使用std::vector<std::vector<int>>
.更好的方法是使用专用的类.但是关键是,一旦摆脱了指针,您就可以毫无问题地返回值:
You are representing a 2D array as a pointer to pointer to int. That is a bad idea. A better idea is to use a std::vector<std::vector<int>>
. Better yet would be to use a dedicated class. But the point is that once you get rid of pointers you can return the value without any problem:
matrix_2d function() {
matrix_2d M = {{1, 2}, {3, 4}};
return M;
}
这对于matrix_2d
的适当定义非常有效(请参见上文).
This works quite well for an appropriate definition of matrix_2d
(see above).
您的代码通过使用指针使整个过程变得更加复杂,并访问了无效的内存.特别是,您要在主函数中分配内存,但随后您要通过重新分配并使用function()
的结果来丢弃指向该内存的指针:在您没有使用先前分配的内存,而是在使用堆栈分配的内存并返回指向该内存的指针.该函数退出后,该堆栈分配的内存就消失了.
Your code makes this whole process much more complicated by using pointers, and accesses invalid memory. In particular, you are allocating memory in your main function, but then you are discarding the pointer to that memory by reassigning it with the result of function()
: inside function
you aren’t using the previously-allocated memory, you are using stack-allocated memory and returning a pointer to that. Once the function exits, that stack-allocated memory is gone.
这篇关于使用类型转换在c ++中返回2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!