开发者

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

开发者 https://www.devze.com 2023-02-18 02:11 出处:网络
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 -

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

?


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;


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


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

精彩评论

暂无评论...
验证码 换一张
取 消