I am back to C from Java and C#. I am stuck with the following simple program attempting to read two arrays from a file with a function. Can anyone point out where am I messing up?
Compiler says:
error: invalid operands to binary * (have ‘int *’ and ‘int *’)
The file format is
4
1 2 3 4
23 23 14 11
My ReadFromFile function needs to fill buffers A and B from the file.
#include<stdio.h>
void ReadFromFile (const char* file_name, int *A, int *B, int *length)
{
FILE* file = fopen (file_name, "r");
fscanf (file, "%d", length);
int i;
for(i = 0; i < length; i++)
{
fscanf (file, "%d", A+i);
}
for(i = 0; i < length; i++)
{
fscanf (file, "%d", B+i);
}
fclose (file);
}
int main()
{
int *A; int *B; int length;
ReadFromFile("input.txt", A, B, &length);
return 0;
}
You have passed in a single integer
Afrommain(), but here you are trying to access completely unrelated memory. Same goes forB. Did you mean to allocateAandBas arrays?e.g. change:
to
or something similar. (Perhaps dynamically allocate the arrays once you know how many you need — or allocate them with
malloc(3)and grow them withrealloc(3)if you need to.)