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:Then to free the array, you have to deallocate everything in reverse: