C++ 声明指向多维数组的指针并分配数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3904224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:01:52  来源:igfitidea点击:

Declaring a pointer to multidimensional array and allocating the array

c++pointersmultidimensional-array

提问by vince88

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.

编译器给我一个错误,指出“somewidth”不能出现在常量表达式中。我尝试了 ** 和 [][] 的各种组合,但它们似乎都不起作用。我知道这并没有那么复杂......感谢任何帮助。

采纳答案by dutt

I just found this ancient answer still gets read, which is a shame since it's wrong. Look at the answer belowwith 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];

回答by Tony The Lion

const int someheight = 3;
const int somewidth = 5;

int (*array)[somewidth] = new int[someheight][somewidth];

回答by Arun

A ready to use example from here, after few seconds of googling with phrase "two dimensional dynamic array":

即用例如从这里,用短语“二维动态数组”使用Google的几秒钟后:

int **dynamicArray = 0;

// memory allocated for elements of rows. 
dynamicArray = new int *[ROWS];

// memory allocated for  elements of each column.  
for( int i = 0 ; i < ROWS ; i++ ) {
    dynamicArray[i] = new int[COLUMNS];
}

// free the allocated memory 
for( int i = 0 ; i < ROWS ; i++ ) {
    delete [] dynamicArray[i];
}
delete [] dynamicArray;

回答by Alexander Rafferty

I suggest using a far simpler method than an array of arrays:

我建议使用比数组数组简单得多的方法:

#define WIDTH 3
#define HEIGHT 4

int* array = new int[WIDTH*HEIGHT];
int x=1, y=2, cell;
cell = array[x+WIDTH*y];

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:

我认为这是比数组数组更好的方法,因为分配要少得多。你甚至可以写一个辅助宏:

#define INDEX(x,y) ((x)+(WIDTH*(y)))

int cell = array[INDEX(2,3)];

回答by Bron Nelson

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.

就我个人而言,我更喜欢使用句法技巧来声明一个指向动态大小的多维数组的指针。这适用于支持可变长度数组 (VLA) 的编译器,所有 C++ 编译器都应该支持可变长度数组,以及大多数当前的 C 编译器。

The basic idea is captured in this:

基本思想体现在:

void bar (int *p, int nz, int ny, int nx) {
  int (*A)[ny][nx] = (int(*)[ny][nx]) p;

"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:

“p”指向您想要视为多维数组的(连续)空间块。“A”与“p”具有相同的值,但该声明使编译器以您想要的多维方式处理对“A”的引用。例如:

#include <iostream>
using namespace std;

void bar (int *p, int nz, int ny, int nx)
{
  int (*A)[ny][nx] = (int(*)[ny][nx]) p;

  for (int ii = 0; ii < nz; ii++) {
    for (int jj = 0; jj < ny; jj++) {
      for(int kk = 0; kk < nx; kk++) {
          A[ii][jj][kk] = ii*1000000 + jj*1000 + kk;
      }
    }
  }
}


void out (int *p, int nz, int ny, int nx)
{
  int (*A)[ny][nx] = (int(*)[ny][nx]) p;
  cout << A[11][22][33] << endl;
}


int main (void)
{
  int NX = 97;
  int NY = 92;
  int NZ = 20;
  int *space = new int [NZ * NY * NX];

  bar (space, NZ, NY, NX);
  out (space, NZ, NY, NX);
  return 0;
}

Running this produces the output "11022033"

运行它会产生输出“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

“A”别名的声明看起来有点奇怪,但它允许您直接简单地使用所需的多维数组语法

回答by Tasdik Rahman

I think this will do

我认为这会做

int r, c ;
std::cin>>r>>c ;
int *array = new int[r*c] ; 

You can input the values by doing something like this

您可以通过执行以下操作来输入值

for (int i = 0 ; i < r ; i++){
    for (int j = 0 ; j < c ; j++){
        std::cin>>array[i *c + j] ; 
    }
}