C ++二维动态数组 [英] C++ 2D Dynamic Array

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

问题描述

我想动态分配一个二维数组的指针在构造函数初始化。

I am trying to dynamically assign a 2d array to a pointer in a constructor initialize.

FooBar::FooBar()
    : _array( new int[10][10] )
{ }
int **_array;

然而,这是行不通的。据我所知,多维数组分配不同的一点。有没有人能详细阐述一下该用解释吗?

However this does not work. I understand that multidimensional arrays are allocated a bit differently. Is anyone able to elaborate on this with an explanation?

先谢谢了。

推荐答案

下面一些答案说二维数组是指向其他数组的数组。这不是真的(在何处存储指针,如果你分配是数组!?的数据)。相反,2-维阵列是其它数组的数组。因此,你必须改变你的会员类型:

Some answers here say a 2-dimensional array is an array of pointers to other arrays. That's not true (where to store pointers, if all you allocate is the data of the array!?). Instead, a 2-dimensional array is an array of other arrays. Thus, you will have to change the type of your member:

FooBar::FooBar()
    : _array( new int[10][10] )
{ }
int (*_array)[10];

这是因为新[] 返回一个指针,创造了一个数组的第一个元素。此元素的10个整数的数组,并且因此部件的类型变化。如果语法让你害怕了,用temlate简化它(这个模板是等同于的boost ::身份)。

That is because new[] returns a pointer to the first element of an array created. This element is an array of 10 integers, and thus the member type change. If the syntax scares you off, simplify it with a temlate (this template is equivalent to boost::identity).

template<typename T> struct identity { typedef T type; };

FooBar::FooBar()
    : _array( new int[10][10] )
{ }
identity<int[10]>::type *_array;

这实际上就像一个就地的typedef。当然,像任何使用新[] ,它需要一个适当的删除[] 放置在析构函数当你的对象被销毁调用。

This effectively works like a in-place typedef. Of course, like with any use of new[], it needs a proper delete[] placed in the destructor and invoked when your object is destroyed.

由于新[] 分配有在编译时已知类型元素的数组,你只能拥有第一个(最外层)的尺寸设置为一个运行值 - 所有其他人必须在编译时已知值。如果这不是你想要的,你将不得不分配指针数组,像一些其他的答案说。

Since new[] allocates an array of elements that have types known at compile time, you can only have the first (most outer) dimension set to a runtime value - all others must have values known at compile time. If that is not what you want, you will have to allocate an array of pointers, like some other answers say.

但注意,为了避免进一步的混乱,那些是的的多维数组。他们是指针的一维数组,其中发生在其他的一维数组点。

But notice, to avoid further confusion, that those are not multi-dimensional arrays. They are single-dimensional arrays of pointers, which happen to point at other single-dimensional arrays.

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

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