You can dynamically allocate memory for a 2-D array as (C99) :
int no_places;
int n = no_places + 1; // for brevity in the following statement
int (*place_table)[n] = malloc(sizeof(int[n][n]));
// check for NULL
if(place_table == NULL) {
// there's a problem
// handle it
}
else {
// you are good to go
}
It won't be correct to reallocate memory for the 2-D array place_table
because with change in the dimension, the values in the older array will be reinterpreted as if they were elements of the new array. This will cause the rows to wrap around. (courtesy Pete Kirkham). Therefore, you need to allocate a new array and copy the values from the old array to it, then free the old array.
int old_n = n;
// value of n has been changed
// allocate a new array
int (*new_place_table)[n] = malloc(sizeof(int[n][n]));
// check for NULL and accordingly proceed
// if not NULL, copy place_table to new_place_table
for(int i = 0; i < old_n; i++) {
for(int j = 0; j < old_n; j++) {
new_place_table[i][j] = place_table[i][j];
}
}
free(place_table);
// do stuff with new_place_table
free(new_place_table);
Also note that you don't need to cast the result of malloc
. There's no benefit of doing this and it can lead to bugs, undefined behaviour and program crash if you forget to include the stdlib.h
header file. Read the details here.