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

查看:33
本文介绍了如何在 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天全站免登陆