声明一个指向多维数组的指针并分配数组 [英] Declaring a pointer to multidimensional array and allocating the array

查看:171
本文介绍了声明一个指向多维数组的指针并分配数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过看,但我还没有找到任何有确定答案的东西。我知道我的问题不能那么难。也许这只是我累了。

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..

基本上,我想声明一个指针到2维数组。我想这样做,因为最终我将不得不调整数组的大小。我已经使用1D数组成功完成了以下操作:

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];

这篇关于声明一个指向多维数组的指针并分配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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