如何创建多维,动态定义的数组?

时间:2011-04-25 08:41:23

标签: c++ arrays pointers multidimensional-array

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

 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/但我对他们所说的完全感到困惑。有人在乎解释吗?非常感谢。

2 个答案:

答案 0 :(得分:3)

我试图通过您的链接提供一些解释:

// 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];

答案 1 :(得分:0)

单维数组的内存布局(比方说有三个元素)看起来像是

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];
}

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