gpt4 book ai didi

c - 使用 fscanf 循环

转载 作者:行者123 更新时间:2023-12-04 06:57:28 24 4
gpt4 key购买 nike

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);

最佳答案

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

// 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);

关于c - 使用 fscanf 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28233395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com