你怎么在C二维数组分配内存++ [英] How do you allocate memory for a 2D array in C++

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

问题描述

嘿,我要分配一些内存为一个二维数组和免费后来在C ++中
我想这样做,因为我在我的节目EX preSSION必须有一个恒定值得到一个错误。

hey I want to allocate some memory for a 2D array and free it later in C++ I want to do this as I am getting an Error in my program " EXPRESSION MUST HAVE A CONSTANT VALUE.

INT X =身高

int y = width;

int pixelArray[x][y];

感谢您。

我在使用Visual Studio 2013

I'm using Visual Studio 2013

推荐答案

天真的方法是分配一个阵列包含行指针,然后分配给每一个行,但是这可能会导致由于内存阵列的性能差局部性。它也可以不以相同的方式作为固定大小的二维数组,这是在存储器中连续使用。

The naive approach is to allocate one array to contain row pointers, and then allocate every single row, but this can lead to poor performance of your array due to memory locality. It also cannot be used in the same way as a fixed-size 2D array, which is contiguous in memory.

所以你可以做的是分配的整数来存储所有的一个数据块,和指针的一个阵列索引它。

So what you can do is allocate one block of integers to hold all the data, and one array of pointers to index it.

int ** my_array = new int*[ x ];
my_array[0] = new int[ x * y ];
for( int i = 1; i < x; i++ )
{
    my_array[i] = my_array[i-1] + y;
}

要清理,你这样做:

delete [] my_array[0];
delete [] my_array;

您应该考虑包装这些功能变成一个简单的类,因为它是维持一个以上的指针。

You should consider wrapping this functionality into a simple class, since it is maintaining more than one pointer.

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

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