While loop with fscanf
12,625
Solution 1
Primary: pass address &
, not value.
// fscanf(m,"%d",data[i++])
fscanf(m,"%d", &data[i++])
Other:
- Check against 1, not
EOF
- Test index limit
- Consider array index as type
size_t
. - No need for casting the result of
malloc()
. Consider malloc style
type *var = malloc(size * sizeof *var)
.int *data = malloc(size * sizeof *data); size_t i=0; while(i < size && fscanf(m,"%d", &data[i++]) == 1);
Solution 2
You need to pass the address:
while(fscanf(m,"%d",&data[i++])!=EOF);
And checking if i < size
is also a good idea.
Comments
-
ElConrado about 2 years
int* data=(int*)malloc(size*sizeof(int)); int i=0,tmp; while(fscanf(m,"%d",&tmp)!=EOF)data[i++]=tmp;
Why it's working instead of this? :
int* data=(int*)malloc(size*sizeof(int)); int i=0; while(fscanf(m,"%d",data[i++])!=EOF);