Home > Back-end >  Error using when using malloc for 2d array in C
Error using when using malloc for 2d array in C

Time:03-16

Why does this show a warning for dereferencing nullptr in C

Level1Tilemap->Map = (int*)((malloc(Level1Columns * sizeof(int))));

for (int i = 0; i < Level1Columns; i  )
{
    Level1Tilemap->Map[i] = malloc(Level1Rows * sizeof(int));

    for (int j = 0; j < Level1Rows; j  )
    {
        Level1Tilemap->Map[i][j] = Level1MapStaticArray[i][j];
    }
}

I am using malloc to create a 2D array of ints

But the editor shows warning and Level1Tilemap->Map has the memory address of nullptr

And the defination int** Map;

CodePudding user response:

You might have meant to use a pointer-to-pointer, in which case sizeof(int) should have been sizeof(int*). However, don't do that, it's obscure and slow, for no good reason.

Instead do

size_t size = sizeof(int[Level1Columns][Level1Rows]);

int (*something)[Level1Rows] = malloc(size);
if(something == NULL) { /* error handling */ }

memcpy(something, Level1MapStaticArray, size);
...
free(something);

Apart from reducing code complexity, this will significantly outperform the code you have currently.

CodePudding user response:

// map is an array of (int*), and the length is column
int** map = (int**) malloc(column * sizeof(int*));

for (int i = 0; i < column;   i) {
    // map[i] is an array of int, and the length is row
    map[i] = malloc(row * sizeof(int*));

    for (int j = 0; j < row;   j)
        map[i][j] = 0;
}
  • Related