声明一个指向多维数组的指针并分配该数组
我尝试过寻找,但没有找到任何明确的答案。我知道我的问题不会那么难。也许只是我累了..
基本上,我想声明一个指向二维数组的指针。我想这样做,因为最终我将不得不调整数组的大小。我已经使用 1D 数组成功完成了以下操作:
int* array;
array = new int[somelength];
我想使用 2D 数组执行以下操作,但它不会编译:
int* array;
array = new int[someheight][somewidth];
编译器给我一个错误,指出“somewidth”不能出现在常量表达式中。我尝试了 ** 和 [][] 的各种组合,但似乎都不起作用。我知道这并不复杂...任何帮助都会受到赞赏。
I've tried looking but I haven't found anything with a definitive answer. I know my problem can't be that hard. Maybe it's just that I'm tired..
Basically, I want to declare a pointer to a 2 dimensional array. I want to do it this way because eventually I will have to resize the array. I have done the following successfully with a 1D array:
int* array;
array = new int[somelength];
I would like to do the following with a 2D array but it won't compile:
int* array;
array = new int[someheight][somewidth];
The compiler gives me an error stating that ‘somewidth’ cannot appear in a constant-expression. I've tried all sorts of combinations of ** and [][] but none of them seem to work. I know this isn't that complicated...Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我刚刚发现这个古老的答案仍然有人阅读,这很遗憾,因为它是错误的。请查看下面的答案以及所有投票。
阅读指针语法,您需要一个数组的数组。这与指向指针的指针是一样的。
I just found this ancient answer still gets read, which is a shame since it's wrong. Look at the answer below with all the votes instead.
Read up on pointer syntax, you need an array of arrays. Which is the same thing as a pointer to a pointer.
在使用短语“two”进行几秒钟谷歌搜索后,来自此处的现成可用示例维动态数组”:
A ready to use example from here, after few seconds of googling with phrase "two dimensional dynamic array":
我建议使用比数组数组简单得多的方法:
我认为这是比数组数组更好的方法,因为分配量要少得多。您甚至可以编写一个辅助宏:
I suggest using a far simpler method than an array of arrays:
I think this is a better approach than an array of an array, as there is far less allocation. You could even write a helper macro:
就我个人而言,我更喜欢使用语法技巧来声明指向动态大小的多维数组的指针。这适用于支持可变长度数组 (VLA) 的编译器(所有 C++ 编译器都应支持该功能)以及大多数当前的 C 编译器。
基本思想如下所示:
“p”指向要视为多维数组的(连续)空间块。 “A”与“p”具有相同的值,但声明使编译器以您想要的多维方式处理对“A”的引用。
例如:
运行此命令会产生输出“11022033”
“A”别名的声明看起来有点奇怪,但它允许您直接简单地使用所需的多维数组语法
Personally, my preference is to use a syntactic trick to declare a pointer to the dynamically sized multi-dimensional array. This works in compilers that support Variable Length Arrays (VLAs), which all C++ compilers should, and most current C compilers.
The basic idea is captured in this:
"p" points at the (contiguous) block of space you want to treat as a multi-dimensional array. "A" has the same value as "p", but the declaration makes the compiler treat references to "A" in the multi-dimensional way you want.
For example:
Running this produces the output "11022033"
The declaration of the "A" alias is a little weird looking, but it allows you to directly and simply use the desired multi-dimensional array syntax
我认为这会做
你可以通过做这样的事情来输入值
I think this will do
You can input the values by doing something like this