C++静态维度数组的动态分配数组
我需要创建一个包含可变数量的“char[2]”的结构,即 2 个字符的静态数组。
我的问题是,如何为 x 个 char[2] 分配内存。
我尝试了这个(假设定义了 int x ):(
char** m = NULL;
m = new char[x][2];
...
delete [] m;
它不起作用)
我意识到我可以使用 std::vector
我对 C++ 很陌生,正在努力学习。
I need to create a structure that holds a variable number of 'char[2]'s, i.e. static arrays of 2 chars.
My question is, how do I allocate memory for x number of char[2].
I tried this (assuming int x is defined):
char** m = NULL;
m = new char[x][2];
...
delete [] m;
(it didn't work)
I realise I could use std::vector<char[2]> as a container, but I'm curious as to how it would be done with raw pointers.
I am very new to C++ and trying to learn.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的代码中,“m”的类型与您的“new”调用不匹配。你想要的是:
m 是一个指向 2 个字符数组的指针,你调用 new 来获取 x 个 2 个字符数组的数组,并将 m 指向第一个字符。
In your code, the type of 'm' doesn't match your 'new' call. What you want is:
m is a pointer to arrays of 2 chars, and you call new to get an array of x arrays of 2 chars and point m at the first one.
我相信下面的代码比
char[n][2]
更具可读性:如果我们了解 wchar 的内部结构,那么如果我们将其声明如下,代码将更具可读性:
最后,因为我们使用 C++,不需要使用 C 数组:
还有一个非常安全的选项,带有编译时间范围检查:
I believe that the following code is more readable than
char[n][2]
:If we aware of the internal structure of wchar, the code will be more readable if we declare it as follows:
And finally, because we use C++, no need to use C arrays:
One more pretty safe option with compile time range checking:
您最终将确定数组的大小,然后使用 new,并将其视为二维数组。
但是,为了对此进行良好的讨论,您可能需要查看:
http://www.velocityreviews.com/forums/t283481-dynamic-多维数组.html
You would end up determining the size of the array, and then use new, and treat it as a two-dimensional array.
But, for a good discussion on this you may want to look at:
http://www.velocityreviews.com/forums/t283481-dynamic-multidimensional-arrays.html
C 多维数组(其中除第一个维度外的所有维度都是常数)是连续排列的。
如果你想要一个(可能是锯齿状的)多维数组,它是一维数组的一维数组,那么你必须循环:
C multi-dimensional arrays (where all but the first dimensions are constant) are laid out contiguously.
If you want a (potentially jagged) multi-dimensional array which is a 1d array of 1d arrays, then you have to loop: