从函数返回多维数组 [英] Returning multidimensional array from function

查看:145
本文介绍了从函数返回多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何返回存储在类的private字段中的多维数组?

How do I return a multidimensional array stored in a private field of my class?

class Myclass {
private:
   int myarray[5][5];
public:
   int **get_array();
};

// This does not work:
int **Myclass::get_array() {
    return myarray;
}

我收到以下错误:

无法将int (*)[5][5]转换为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];
}

在这里,我们有五个指针组成的数组,每个指针指向一个单独的内存块(总共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.

这篇关于从函数返回多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆