I am trying to allocate the row dimension of an array (a
) to the size of a user input value. Here is the code I have:
#include <stdio.h>
#include <stdlib.h>
void FreeArray(int **arry, int N);
int main() {
int **a;
int **b;
int N_a;
int N;
if (a != NULL) {
FreeArray(a, N);
}
if (b != NULL) {
FreeArray(b, N);
}
do {
printf("Enter the size of the NxN array:\n");
scanf("%d", &N);
if (N < 2) {
printf("Error, enter correct size.\n");
}
} while (N < 2);
N_a = N;
int errorInAlloc = 0;
a = (int**)malloc(N_a * sizeof(int*));
if (a != NULL) {
errorInAlloc = 1;
}
return 0;
}
void FreeArray(int **arr, int N) {
int i;
if (arr == NULL)
return;
if (arr != NULL) {
for (i = 0; i < N; i++) {
if (arr[i] != NULL)
free(arr[i]);
}
free(arr);
}
}
The FreeArray
function was provided to us, so I know it is correct. There is other code included in this, but I omitted is since it is just a menu. When I comment out a = (int**) malloc(N_a * sizeof(int*));
the program compiles and runs without crashing or problems. When I include this line, the program compiles, but when I put a number greater than or equal to 2, it crashes. I have also tried a = malloc(N_a * sizeof(int*));
and a = (int**)malloc(N * sizeof(int*));
AND a = malloc(N * sizeof(int*));
but all do the same thing.
I have been coding and running the program in Code::Blocks, but even when I compile it through the command prompt, it still crashes.
I have a hard time with arrays on a good day, so dynamically allocating arrays is so confusing to me, any help is greatly appreciated!