【问题标题】:how to create multidimensional, dynamically defined array?如何创建多维、动态定义的数组?
【发布时间】:2011-04-25 08:41:23
【问题描述】:

我知道如何创建一维动态定义的数组

 string *names = new string[number]; //number specified by the user

然而,当我试图让它成为多维的时候

 string *names = new string[number][number]; //doesn't work

它不起作用。是什么赋予了?我找到了这个http://www.cplusplus.com/forum/beginner/63/,但我完全被他们所说的弄糊涂了。有人愿意解释吗?非常感谢。

【问题讨论】:

标签: c++ arrays pointers multidimensional-array


【解决方案1】:

我试图从您的链接中为示例提供一些解释:

// To dynamically allocate two-dimensional array we will allocate array of pointers to int first. 
// Each pointer will represent a row in your matrix.
// Next step we allocate enough memory for each row and assign this memory for row pointers.

const int rows = 4; //number of rows in your matrix
const int cols = 4; //number of columns in your matrix

// declaration
int ** a; 

/* allocating memory for pointers to rows. Each row will be a dynamically allocated array of int */
a = new int*[rows];
/* for each row you allocate enough memory to contain cols elements. cols - number of columns*/ 
for(int i = 0; i < rows; i++)
   a[i] = new int[cols];

【讨论】:

  • 非常感谢您。我目前正在消化......但与此同时,我可以问一下 int **a 是什么,而不是 int *a?谢谢。
  • 是的,它是一个指向 int 的指针。这意味着,如果我们有int **ppint,那么 '*ppint' 是一个指向 int 的指针。 **ppint 是整数。例如,我们可以这样做:int *pint = *ppint.
  • 谢谢。我仍然对如何访问多维数组中的数据感到困惑。做 cout
  • 没关系!我的愚蠢错误,非常感谢您的帮助
【解决方案2】:

一维数组(比如说三个元素)的内存布局是这样的,

names ------> [0] [1] [2] 

二维数组(假设有 3 X 3 个元素)看起来像,

names ------> [0] --> [0] [1] [2] 
              [1] --> [0] [1] [2]
              [2] --> [0] [1] [2]
               ^
               |
           this is an array of pointers

即二维数组是指向数组的指针数组,因此您首先需要**名称。

string **names = new string*[number]; // allocating space for array of string pointers

现在,您希望这个字符串指针数组的每个元素都指向一个字符串数组。

因此,您需要这样做

for(int i = 0; i < number, i++) {
   names[i] = new string[number];
}

我希望这有助于更好地理解它。

【讨论】:

    猜你喜欢
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2020-07-21
    • 2022-01-02
    • 2014-08-14
    • 2017-12-10
    相关资源
    最近更新 更多