在c ++中动态分配2D数组的行 [英] dynamic allocation of rows of 2D array in c++

查看:198
本文介绍了在c ++中动态分配2D数组的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++中,我可以创建一个具有固定列数(如5)的二维数组,如下所示:

In c++, I can create a 2D array with fixed number of columns, say 5, as follows:

char (*c)[5];

然后我可以按如下方式为行分配内存:

then I can allocate memory for rows as follows

c = new char[n][5];

其中n可以是任何可以在运行时赋值的变量。我想知道是否以及如何使用此方法动态分配可变量的内存到每行。即我想使用第一个语句,但可以修改第二个语句。

where n can be any variable which can be assigned value even at run time. I would like to know whether and how can I dynamically allocate variable amount of memory to each row with this method. i.e. I want to use first statement as such but can modify the second statement.

推荐答案

'd做一个指针指针,用一个指针数组来填充,每个指针的数组被填充一个char数组:

Instead of a pointer to an array, you'd make a pointer to a pointer, to be filled with an array of pointers, each element of which is in turn to be filled with an array of chars:

char ** c = new char*[n];  // array of pointers, c points to first element

for (unsigned int i = 0; i != n; ++i)
    c[i] = new char[get_size_of_array(i)]; // array of chars, c[i] points to 1st element

是一个 std :: vector< std :: string>

分配有 new [] 不能调整大小,因为在C ++中没有类似 realloc 感觉与对象模型,如果你想到它)。因此,在动态生命周期管理时,应始终优先使用合适的容器。

As you noticed in the comment, dynamic arrays allocated with new[] cannot be resized, since there is no analogue of realloc in C++ (it doesn't make sense with the object model, if you think about it). Therefore, you should always prefer a proper container over any manual attempt at dynamic lifetime management.

总之:不要使用 new 。永远。使用适当的动态容器。

In summary: Don't use new. Ever. Use appropriate dynamic containers.

这篇关于在c ++中动态分配2D数组的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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