The line *array[cnt] = thing causes a seg fault and I don’t know why. Any ideas to fix this?
long *Load_File(char *Filename, int *Size)
{
FILE *fp;
if((fp = fopen(Filename,"r")) == NULL)
{
printf("Cannot open file.\n");
exit(-1);
}
fscanf(fp,"%d",Size);
int cnt = 0;
int items = *Size;
long * array[items];
int thing;
while (!feof(fp))
{
fscanf(fp,"%d",&thing);
*array[cnt] = thing;
cnt++;
}
fclose(fp);
return *array;
}
is declaring an array of pointers to long data type. But these pointers are not pointing to anything meaningful.
When you do
you are dereferencing the pointer which is incorrect since they dont point to anything meaningful.
You can dynamically allocate the memory for the array as:
and then do:
and then return the array as: