C ++从函数返回多维数组 [英] C++ Returning multidimension array from function
问题描述
如何返回隐藏在私有字段中的多维数组?
How do I return a multidimensional array hidden in a private field?
class Myclass {
private:
int myarray[5][5];
public:
int **get_array();
};
........
int **Myclass::get_array() {
return myarray;
}
无法转换 int(*)[5] 5]
到 int **
在返回test.cpp / Polky / src line 73 C / C ++ Problem
cannot convert int (*)[5][5]
to int**
in return test.cpp /Polky/src line 73 C/C++ Problem
推荐答案
二维数组不会衰减为指向int的指针。它衰减到指向int数组的指针 - 也就是说,只有第一维衰减为指针。指针不指向int指针,当以指针的大小递增时,指向5个整数的数组。
A two-dimensional array does not decay to a pointer to pointer to ints. It decays to a pointer to arrays of ints - that is, only the first dimension decays to a pointer. The pointer does not point to int pointers, which when incremented advance by the size of a pointer, but to arrays of 5 integers.
class Myclass {
private:
int myarray[5][5];
public:
typedef int (*pointer_to_arrays)[5]; //typedefs can make things more readable with such awkward types
pointer_to_arrays get_array() {return myarray;}
};
int main()
{
Myclass o;
int (*a)[5] = o.get_array();
//or
Myclass::pointer_to_arrays b = o.get_array();
}
指向指针的指针( int ** <
A pointer to pointer (int**
) is used when each subarray is allocated separately (that is, you originally have an array of pointers)
int* p[5];
for (int i = 0; i != 5; ++i) {
p[i] = new int[5];
}
这里我们有一个5个指针数组,每个指针指向第一个项目一个单独的内存块,共有6个不同的内存块。
Here we have an array of five pointers, each pointing to the first item in a separate memory block, altogether 6 distinct memory blocks.
在二维数组中,您将获得一个连续的内存块:
In a two-dimensional array you get a single contiguous block of memory:
int arr[5][5]; //a single block of 5 * 5 * sizeof(int) bytes
这些东西的布局完全不同,因此这些东西不能以同样的方式返回和传递。
You should see that the memory layout of these things are completely different, and therefore these things cannot be returned and passed the same way.
这篇关于C ++从函数返回多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!