用fscanf循环

时间:2015-01-30 10:03:26

标签: c memory malloc scanf

int* data=(int*)malloc(size*sizeof(int));
int i=0,tmp;
while(fscanf(m,"%d",&tmp)!=EOF)data[i++]=tmp;

为什么它的工作而不是这个? :

int* data=(int*)malloc(size*sizeof(int));
int i=0;
while(fscanf(m,"%d",data[i++])!=EOF);

2 个答案:

答案 0 :(得分:5)

主要:传递地址&,而不是值。

// fscanf(m,"%d",data[i++])
fscanf(m,"%d", &data[i++])

其他:

  • 检查1,而不是EOF
  • 测试索引限制
  • 将数组索引视为类型size_t
  • 无需投射malloc()
  • 的结果
  • 考虑malloc样式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);
    

答案 1 :(得分:3)

您需要传递地址:

while(fscanf(m,"%d",&data[i++])!=EOF);

检查i < size是否也是一个好主意。