0

Purpose of my program is simple, to read sequence of int numbers from file, here's the code:

int main()
{
   FILE *file = fopen("test.txt", "r");

   int *array = NULL; // Declaration of pointer to future array;
   int count;

   process_file(file, array, &count);

   return 0;
}

// Function returns 'zero' if everything goes successful plus array and count of elements as arguments
int process_file(FILE *file, int *arr, int *count)
{
    int a;
    int i;
    *count = 0;

    // Function counts elements of sequence
    while (fscanf(file, "%d", &a) == 1)
    {
        *count += 1;
    }

    arr = (int*) malloc(*count * sizeof(int)); // Here program allocates some memory for array

    rewind(file);

    i = 0;
    while (fscanf(file, "%d", &a) == 1)
    {
        arr[i] =  a;
        i++;
    }

    fclose(file);

    return 0;
}

Problem is, in outer function (main), array haven't changed. How could it be fixed?

jl284
  • 61
  • 5

1 Answers1

4

You need to pass the array by reference, so that the function can change its caller's array.

It must be:

process_file(FILE *file, int **arr, int *count)

and call like so:

process_file(file, &array, &count);

Additionally, I would suggest:

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606