如何在 C++ 中分配一个二维指针数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1768294/
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-27 21:08:04  来源:igfitidea点击:

How to allocate a 2D array of pointers in C++

c++pointersallocationmultidimensional-array

提问by TheFuzz

I'm trying to make a pointer point to a 2D array of pointers. What is the syntax and how would I access elements?

我试图让一个指针指向一个二维指针数组。什么是语法以及如何访问元素?

回答by Drew Hall

By the letter of the law, here's how to do it:

根据法律条文,这是如何做到的:

// Create 2D array of pointers:
int*** array2d = new (int**)[rows];
for (int i = 0; i < rows; ++i) {
  array2d[i] = new (int*)[cols];
}

// Null out the pointers contained in the array:
for (int i = 0; i < rows; ++i) {
  for (int j = 0; j < cols; ++j) {
    array2d[i][j] = NULL;
  }
}

Be careful to delete the contained pointers, the row arrays, and the column array all separately and in the correct order.

小心地以正确的顺序分别删除包含的指针、行数组和列数组。

However, more frequently in C++ you'd create a class that internally managed a 1D array of pointers and overload the function call operator to provide 2D indexing. That way you're really have a contiguous array of pointers, rather than an array of arrays of pointers.

但是,在 C++ 中,您更频繁地创建一个类,该类在内部管理一维指针数组并重载函数调用运算符以提供二维索引。这样你就真的有一个连续的指针数组,而不是一个指针数组的数组。

回答by Martin York

It depends. It can be as simple as:

这取决于。它可以很简单:

int main()
{
    int*   data1[10][20]; // Fixed size known at compile time

    data1[2][3] = new int(4);
}

If you want dynamic sizes at runtime you need to do some work.
But Boosthas you covered:

如果您想要在运行时动态大小,您需要做一些工作。
但是Boost已经涵盖了:

int main()
{
   int  x;
   int  y;
   getWidthAndHeight(x,y);

   // declare a 2D array of int*
   boost::multi_array<int*,2>   data1(boost::extents[x][y]);

   data[2][3] = new int(6);
}

If you are fine with jagged arraysthat can grow dynamically:

如果您对可以动态增长的锯齿状数组感到满意:

int main()
{
    std::vector<std::vector<int*> >   data1;

    data1.push_back(std::vector<int*>(10,NULL));
    data1[0][3] = new int(7);
}

Note:In all the above. I assume that the array does not own the pointer. Thus it has not been doing any management on the pointers it contains (though for brevity I have been using new int() in the examples). To do memory management correctly you need to do some more work.

注:以上所有。我假设数组不拥有指针。因此它没有对其包含的指针进行任何管理(尽管为了简洁起见,我在示例中一直使用 new int() )。要正确进行内存管理,您需要做更多的工作。

回答by Crashworks

int *pointerArray[X][Y];
int **ptrToPointerArray = pointerArray;

That's how you make a true (contiguous in memory) multidimensional array.

这就是你如何制作一个真正的(在内存中连续的)多维数组。

But realize that once you cast a multidimensional array to a pointer like that, you lose the ability to index it automatically. You would have to do the multidimensional part of the indexing manually:

但是要意识到,一旦将多维数组转换为这样的指针,就失去了自动索引它的能力。您必须手动执行索引的多维部分:

int *pointerArray[8][6]; // declare array of pointers
int **ptrToPointerArray = &pointerArray[0][0]; // make a pointer to the array
int *foo = pointerArray[3][1]; // access one element in the array
int *bar = *(ptrToPointerArray + 3*8 + 1); // manually perform row-major indexing for 2d array

foo == bar; // true
int *baz = ptrToPointerArray[3][1]; // syntax error

回答by Hans Passant

double** array = new double*[rowCnt];
for (int row = 0; row < rowCnt; ++row)
  array[row] = new double[colCnt];
for (int row = 0; row < rowCnt; ++row)
  for (int col = 0; col < colCnt; ++col)
    array[row][col] = 0;

回答by Chip

You could try Boost::MultiArray.

你可以试试 Boost::MultiArray。

Check out this pagefor details.

查看此页面了解详细信息。

回答by Charles Beattie

I prefer to use the () operator. There are lots of reasons for this (C++ FAQs 13.10). Change the internal representation to a std::vectorif you like:

我更喜欢使用 () 运算符。这有很多原因(C++ FAQs 13.10)。std::vector如果您愿意,请将内部表示更改为 a :

template <class T, int WIDTH, int HIEGHT>
class Array2d
{
public:
    const T& operator ()(size_t col, size_t row) const
    {
        // Assert col < WIDTH and row < HIEGHT
        return m_data [( row * WIDTH + col)];
    }
    T& operator ()(size_t col, size_t row)
    {
        // Assert col < WIDTH and row < HIEGHT
        return m_data [( row * WIDTH + col)];
    }
private:
T m_data[WIDTH * HIEGHT];
};

You can use it like this:

你可以这样使用它:

Array2d< Object*, 10, 10 > myObjectArray;
myObjectArray(5,6) = new Object();

回答by xtofl

:)

:)

I had these once in a piece of code I wrote.

我曾经在我写的一段代码中使用过这些。

I was the laughing stock of the team when the first bugs leaked out. On top of that we use Hungarian notation, leading to a name like papChannel- a pointer to an array of pointers...

当第一个错误泄露时,我是团队的笑柄。最重要的是,我们使用匈牙利表示法,导致名称类似于papChannel- 指向指针数组的指针......

It's not nice. It's nicer to use typedefs to define a 'row of columns' or vice versa. Makes indexing more clear, too.

这不好。最好使用 typedef 来定义“一行列”,反之亦然。也使索引更加清晰。

typedef int Cell;
typedef Cell Row[30];
typedef Row Table[20];

Table * pTable = new Table;

for( Row* pRow = *pTable; pRow != *pTable+_countof(*pTable); ++pRow ) {
   for( Cell* pCell = *pRow; pCell != *pRow + _countof(*pRow); ++pCell ) {
     ... do something with cells.
   }
}

回答by Elalfer

You can define a vector of vectors:

您可以定义向量的向量:

typedef my_type *my_pointer;

typedef vector<vector<my_pointer> > my_pointer2D;

Than create a class derived from my_pointer2D, like:

比创建一个派生自 my_pointer2D 的类,例如:

class PointersField: public my_pointer2D
{
  PointsField(int n, int m)
  {
     // Resize vectors....
  }
}

PointsField pf(10,10); // Will create a 10x10 matrix of my_pointer

回答by Test

See my code. It works on my FC9 x86_64 system:

看我的代码。它适用于我的 FC9 x86_64 系统:

#include <stdio.h>

template<typename t>
struct array_2d {
        struct array_1d {
                t *array;
                array_1d(void) { array = 0; }
                ~array_1d()
                {
                    if (array) {
                         delete[] array;
                         array = 0;
                    }
                }
                t &operator[](size_t index) { return array[index]; }
        } *array;
        array_2d(void) { array = 0; }
        array_2d(array_2d<t> *a) { array = a->array; a->array = 0; }
        void init(size_t a, size_t b)
        {
                array = new array_1d[a];
                for (size_t i = 0; i < a; i++) {
                        array[i].array = new t[b];
                }
        }
        ~array_2d()
        {
                if (array) {
                        delete[] array;
                        array = 0;
                }
        }
        array_1d &operator[](size_t index) { return array[index]; }
};

int main(int argc, char **argv)
{
        array_2d<int> arr = new array_2d<int>;
        arr.init(16, 8);

        arr[8][2] = 18;
        printf("%d\n",
                arr[8][2]
                );

        return 0;
}

Effo UPD: a response to "Isn't that an array of pointers to arrays?", adding the example of array of pointers, very simple:

Effo UPD:对“这不是指向数组的指针数组吗?”的回应,添加了指针数组的例子,很简单:

int main(int argc, char **argv)
{
        array_2d<int*> parr = new array_2d<int*>;
        int i = 10;
        parr.init(16, 8);
        parr[10][5] = &i;
        printf("%p %d\n",
                parr[10][5],
                parr[10][5][0]
                );

        return 0;
}

Did I still misunderstand your question?

我还是误解了你的问题吗?

And you could even

你甚至可以

typedef array_2d<int*> cell_type;
typedef array_2d<cell_type*> array_type;

int main(int argc, char **argv)
{
    array_type parr = new array_type;
    parr.init(16, 8);
    parr[10][5] = new cell_type;
    cell_type *cell = parr[10][5];
    cell->init(8, 16);
    int i = 10;
    (*cell)[2][2] = &i;

    printf("%p %d\n",
            (*cell)[2][2],
            (*cell)[2][2][0]
            );

    delete cell;

    return 0;
}

It also works on my FC9 x86_64 system.

它也适用于我的 FC9 x86_64 系统。