需要有关C ++中二维数组的动态内存分配的帮助 [英] Need help regarding Dynamic Memory Allocation for two dimensional arrays in C++

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

问题描述

我一直在尝试为二维数组分配动态内存。经过大量搜索后,我发现一个比其他代码看起来更容易的代码,但我仍然无法理解它的每个细节。有人可以解释一下以下代码如何将内存动态分配给数组。真的很期待获得帮助和对不起,但是我是C ++的新手,想学习它。

I had been trying to allocate dynamic memory for a two-dimensional array. After searchin a lot I've found a code that looks easier than others still I'm unable to understand each and every detail of it. Can someone explain me how does the following code assigns memory to the array dynamically. Really looking forward for help and sorry but I'm new to C++ and want to learn it.

void main()
{
int m,n;
cin>>m;
cin>>n;
//Allocate
int *a = new int[m*n];
//Use a[m][n]
for( int i = 0 ; i < m ; i++)
        for ( int j = 0 ; j < n ; j++)
                 a[i*n + j] = 1;
}


推荐答案

首先,您要做什么正在做,就是将1插入一维数组的不同插槽中。

First of all, what you're doing, is adding 1 to different slots of a ONE-dimensional array.

以下是代码的注释版本:

Here's a commented version of your code:

int *a = new int[m*n];  // declares a pointer a, that points to a newly 
                        // allocated space on the heap, for an array of size m*n.


for( int i = 0 ; i < m ; i++)        // loop through m number of times
    for ( int j = 0 ; j < n ; j++)   // loop through n number of times PER m
             a[i*n + j] = 1;         // assigns 1 to a spot [i*n + j]

这就是您制作动态图片的方式二维数组(换句话说就是指向数组的指针数组):

THIS is how you make a dynamic 2D array (in other words, array of pointers to arrays):

const int sizeX = 10;
const int sizeY = 5;

int** arrayOfPointers = new int*[sizeX];
for(int i = 0; i < sizeX; i++)
    arrayOfPointers[i] = new int[sizeY];

然后,您可以使用双循环(未测试)向该数组添加多个元素:

Then, you can add multiple elements to that array using a double loop (NOT TESTED):

for(int i = 0 ; i < sizeY ; i++)        // loop through all the rows
    for (int j = 0 ; j < sizeX ; j++)   // loop through all columns for row i
         arrayOfPointers[i][j] = i*j; // assigns i*j to a spot at row i, column j

这是打印方式取出2D数组的内容:

This is how you can print out the contents of the 2D array:

for(int i = 0 ; i < sizeY ; i++) { 

    for (int j = 0 ; j < sizeX ; j++)   
         cout << arrayOfPointers[i][j];

    cout << endl; // go to the next line when the row is finished

}

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

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