Search code examples
carrayspointersmallocrealloc

How to increase array size that has global pointer in each loop


I want to set the size of an array as the first integer in a text file (say 5). If I saved all the 5 integers that follow the size into the array, and there is still lines in the input file, I need to increase the size of the array each time and store that line (integer) in the array. I wrote this code:

int *x;
int *sizeP;
int main(int argc, char *argv[]) {

    int decision;
    FILE* file = fopen( argv[1], "r" );
    int size;
    fscanf(file, "%d", &size);
    sizeP = &size;              
    x=malloc(size*sizeof(int));
    int p=0;
    int num;

    while(fscanf(file, "%d", &num) ) {
        x[p] = num;
        p++;
        if (p >= size) {
            puts("Enter 0 to continue or 1 to terminate");
            scanf("%d", &decision);
            break;
        }
    }
    if (decision == 0){
        while(fscanf(file, "%d", &num) ) {
            size++;
            x = (int*)realloc(x, size*sizeof(int));
            x[p] = num;
            p++;
        }
        free(x);
    }
}

I am not sure what is wrong with this code?

Thank you in advance.


Solution

  • Your way of checking the result of fscanf is not correct. When the end of file is reached, fscanf does not return 0, but EOF, which is not zero (it is defined as -1 on most platforms).

    while(fscanf(file, "%d", &num) )

    This will enter an infinite loop once the end of the file is reached, because since EOF is not zero, its boolean value is true.

    The correct way to check the result of fscanf is to compare it with the number of fields expected. Since you are reading one value, you should the return like like this:

    while(fscanf(file, "%d", &num) == 1) // <-- return value should be 1 on success