Hi. Im quite new to c programming. Im trying to figure out how to use malloc. I saw a question similar to this in the forum but it was a good bit more complicated and I didnt really understand it.
I want to create a 1D array of ints from a file. I had a stab at it but the while loop isnt correct, am going about it the right way?
Code:#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fid;
int * iarray;
int n=0;
fid = fopen("unsorted.txt", "r");
if (fid == NULL)
{
printf("Cannot open file\n");
exit(EXIT_FAILURE);
}
iarray = (int *) malloc ( n * sizeof(int) );
iarray[n] = fgets(fid);
while( ( iarray[n] = fgets(fid) ) != EOF )
/*or ? while(fscanf(fid, "%s", &iarray[n]) != EOF )*/
{
fscanf(fid, "%d", &iarray[n]);
n++;
}
fclose(fid);
printf("%d", iarray[n]);
return(0);
}

