Declaring a pointer to multidimensional array and allocating the array(声明指向多维数组的指针并分配数组)
问题描述
我试过寻找,但没有找到任何明确的答案.我知道我的问题不可能那么难.也许只是我累了..
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];
编译器给我一个错误,指出‘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.
推荐答案
我刚刚发现这个古老的答案仍然被阅读,这是一种耻辱,因为它是错误的.看看下面的答案,而不是所有的选票.
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.
int width = 5;
int height = 5;
int** arr = new int*[width];
for(int i = 0; i < width; ++i)
arr[i] = new int[height];
这篇关于声明指向多维数组的指针并分配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声明指向多维数组的指针并分配数组
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
