pauliwago
pauliwago

Reputation: 6655

how to create multidimensional, dynamically defined array?

i know how to create a single-dimensional, dynamically defined array

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

however, when i try to make it multidimensional

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

it doesn't work. what gives? i found this http://www.cplusplus.com/forum/beginner/63/ but am completely confused by what they are saying. anyone care to explain? thanks so much.

Upvotes: 0

Views: 1489

Answers (2)

sahaj
sahaj

Reputation: 842

The memory layout of single-dimension array (let's say with three elements) looks like,

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

And the two-dimensional array (let's say with 3 X 3 elements) would look like,

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

i.e. two dimensional array is array of pointers to arrays, therefore you would need **names in first place.

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

Now, you want each element of this array of string pointers to point to an array of strings.

Therefore, you would need to do

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

I hope this helps to understand it better.

Upvotes: 0

beduin
beduin

Reputation: 8253

I tried to provide some explanations to example from your link:

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

Upvotes: 3

Related Questions