Sterling
Sterling

Reputation: 45

Convert char** to char[x][x]

In C++, I want my class to have a char** field that will be sized with user input. Basically, I want to do something like this -

char** map;
map = new char[10][10];

with the 10's being any integer number. I get an error saying cannot convert char*[10] to char**. Why can it not do this when I could do -

char* astring;
astring = new char[10];

?

Upvotes: 2

Views: 1358

Answers (3)

winterTTr
winterTTr

Reputation: 1768

On other hand, what the

map = new char[x][y];

really do is that, you new a array contain x items whose type is an array containing y items. And y must be a const integer.

So, if you really want your code pass without any problem, the correct way is

char (* map)[10] ;
map = new char[some_value_you_want][10];

Or more clearly,

typedef char array10[10];
array10 * map = new array10[some_value_you_want];

Upvotes: 1

Adam Rosenfield
Adam Rosenfield

Reputation: 400194

Because an array is not a pointer. Arrays decay into pointers to their first elements, but that happens only at the first level: a 2D array decays into a pointer to a 1D array, but that's it—it does not decay into a pointer to a pointer.

operator new[] allows to allocate a dynamic array of a size only known at runtime, but it only lets you allocate 1D arrays. If you want to allocate a dynamic 2D array, you need to do it in two steps: first allocate an array of pointers, then for each pointer, allocate another 1D array. For example:

char **map = new char*[10];  // allocate dynamic array of 10 char*'s
for(int i = 0; i < 10; i++)
    map[i] = new char[10];  // allocate dynamic array of 10 char's

Then to free the array, you have to deallocate everything in reverse:

for(int i = 0; i < 10; i++)
    delete [] map[i];
delete [] map;

Upvotes: 6

Avilo
Avilo

Reputation: 1204

Multi-dimentional arrays are not supported in that manner. You need to allocate the two dimentions seperately.

char** map = new (char*)[10];

for( int i = 0; i < 10; ++i ) {
  map[i] = new char[10];
}

Upvotes: -1

Related Questions