0

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.

pauliwago
  • 6,373
  • 11
  • 42
  • 52

2 Answers2

3

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];
beduin
  • 7,943
  • 3
  • 27
  • 24
  • thank you so much for this. i'm currently digesting...but in the meanwhile, may i ask what int **a is as opposed to int *a? thankyou. – pauliwago Apr 25 '11 at 09:02
  • yeah, it is a pointer to pointer to int. It means, that if we have `int **ppint`, then '*ppint' is a pointer to int. And **ppint is int. We can for example do this: `int *pint = *ppint`. – beduin Apr 25 '11 at 09:09
  • thanks. i'm still confused as to how to access the data in the multidimensional array. doing cout << elements[0][3]; doesn't work, for example (it prints out the address i believe, which makes sense i guess since they're pointers and pointers store addresses) – pauliwago Apr 25 '11 at 09:18
0

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.

sahaj
  • 822
  • 5
  • 17