I have the next code which I want to read an 2D array. It does this, but after the program ends the program crashes every time. I have a bigger program, but here is the only problem. I have also read Correctly allocating multi-dimensional arrays and I debugged the program.
The question is: why does the program crash at the end even it throughout the expected operation procedure it works fine?
void dynamicMemAlloc(int n, int (**arrayPointer)[n][n]){
*arrayPointer = malloc(sizeof(int[n][n]));
assert(*arrayPointer != NULL);
}
void readMy2Darray(int n, int array[n][n]){
int i, j;
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
scanf("%d", &array[i][j]);
}
void printMy2Darray(int n, int array[n][n]){
int i, j;
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++)
printf("%d ", array[i][j]);
printf("\n");
}
}
int main(void){
int n;
printf("Read the dimension(n): ");
scanf("%d", &n);
int (*arrayPointer)[n][n];
dynamicMemAlloc(n, &arrayPointer);
printf("Read the 2D array:\n");
readMy2Darray(n, *arrayPointer);
printf("Printed array:\n");
printMy2Darray(n, *arrayPointer);
free(arrayPointer);
return 0;
}