如何在C ++中分配二维数组的指针 [英] How to allocate a 2D array of pointers in C++

查看:137
本文介绍了如何在C ++中分配二维数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个指针指向二维数组的指针。

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

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

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 ++中分配二维数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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