1

Newbie question here...why does the following code only work with a 1D array but not a 2D array? Shouldn't it not make a difference whether b is pointing to the start of a 1D array or a 2D array, as long as it's a char* pointer (as it is)? I thought that the general notation [bound1][bound2] was an equivalent of [bound1*bound2], even over the assignment operation. Help?

main() //this works fine 
    {
        char *b;
        b = new char[50];
        return 0;
    }

.

main() //but this raises the error "Cannot convert char(*)[50] to char* in assignment"
{
    char *b;
    b = new char[50][50];
    return 0;
}
  • 1
    Sometimes it helps if you search SO - http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new – SChepurin Oct 26 '13 at 13:41

2 Answers2

0

char[50]; is array of 50 elements of type char. Each element has type char. So new char[50]; returns a pointer to first element: char * - pointer to char.

char[50][50] is NOT array of char. It is array of arrays. Each element has type char[50]. So new char[50][50]; returns a pointer to first element: char (*)[50] - pointer to char[50].

Declare b this way:

char (*b)[50];

Test: http://ideone.com/1zJs1O

kotlomoy
  • 1,420
  • 8
  • 14
0

If your were right with that [bound1][bound2] and [bound1*bound2] were equivalent you wouldn't have created a 2D array. The size of allocated memory, that's what your multiplication implies, is not the problem here, it's about different data types: A 1D array is simply not a 2D array and that's what the compiler is telling you. You should read about C++ type system and type safety.

What is type safety and what are the "type safe" alternatives?

Community
  • 1
  • 1
Thorsten Schöning
  • 3,501
  • 2
  • 25
  • 46