I've been looking at other answers of similar nature here but still run into problems.
I am a beginner in C and need some advice.
Relevant parts of code:
int readNumbers(int **array, char* fname, int hexFlag) {
int numberRead = 0;
FILE* fp;
int counter = 0;
char arr[100];
char* ptr;
array = malloc(0 * sizeof(*array)); //Problematic area. Should I initially give it space?
fp = fopen(fname, "r");
if (fp == NULL) {
printf("Error opening file\n");
return -1;
}
while (fgets(arr, sizeof(arr), fp)) {
ptr = strtok(arr, " \n");
while(ptr) {
if (hexFlag == 0) {
array = realloc(array, (counter + 1) * sizeof(int*));
array[counter++] = strtol(ptr , NULL , 10); //Seg Faulting
} else {
array = realloc(array, (counter + 1) * sizeof(int*));
array[counter++] = strtol(ptr, NULL, 16);
}
++numberRead;
ptr = strtok(NULL , " \n");
}
}
I debugged this and it seems that the array never gets memory allocated to it. Also, the program seg faults right after I try to access array by array[counter++]
;
I also found out it is bad practice to realloc after each increment, but I don't know what else to do.