动态分配2D数组而不使用任何循环? [英] Dynamically allocate 2D array without using any loops?

查看:167
本文介绍了动态分配2D数组而不使用任何循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以动态分配二维数组,而不使用任何for循环或while循环?
i在c c ++中有任何直接命令或函数?

Can we dynamically allocate 2D array without using any for loop or while loops? i there any direct command or function in c c++?

推荐答案

c ++即一维的大小必须在编译时确定。然后这个分配可以在单个语句中完成,如下所示:

Without using a loop you will have one restriction in ISO c++ i.e. size of one dimension has to be determined at compile time. Then this allocation can be done in a single statement as follows:

#define COLUMN_SIZE 10 // this has to be determined at compile time
int main()
{
    int (* arr)[COLUMN_SIZE];
    int rows = 20; // this is dynamic and can be input from user at run time
    arr = new int[rows][COLUMN_SIZE];
    arr[3][4] = 10;
    cout << arr[3][4] << endl;
    return 0;
}

分配给的内存需要释放。此外,如果我们将其扩展到n维,则可以在运行时确定这些维度中的只有一个。原因是编译器必须知道每行的大小才能创建一行连续的内存。

The memory allocated with new needs to be freed. Also if we extend it to n dimensions, only one of these dimensions can be determined at run time. The reason is that compiler has to know the size of each row in order to create a row of contiguous memory.

这篇关于动态分配2D数组而不使用任何循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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