【问题标题】:rewriting a file using function fprint and an int array使用函数 fprint 和 int 数组重写文件
【发布时间】:2015-10-28 12:34:13
【问题描述】:

我想使用 fprintf 用 int 数组的内容覆盖文件。这应该是一个非常简单的程序,但是,我没有得到预期的输出。请不要建议使用其他函数,因为这是一个 uni 赋值,我们必须使用数组和 fprintf。

所以虽然我希望文件包含:

3 3 3 3 3 3 3 3 3 3 3 3 

我明白了:

1495894796 1495894796 1495894796 1495894796 1495894796 1495894796 
1495894796 1495894796 1495894796 1495894796 1495894796 1495894796

还有这个编译器警告:

  format specifies type 'int' but the argument has type 'int *' [-Wformat]

我不知道是什么导致了这个错误,因为我有一个运行良好的非常相似的程序,但是我使用了一个 char 数组和函数 fputc。

这是我代码的相关部分,如有需要,请随时索取完整代码:

    #include<stdio.h>
    #include<stdlib.h>

    #define ARRAY_ELEMENTS 13
    /* Defining the size of my int array */

    int main(){
      int i, aux;
      FILE *finformation
      int defined_array[ARRAY_ELEMENTS];

      i = 0;

      while (i < (ARRAY ELEMENTS - 1))
      {
          defined_array[i] = 3;
          i = i+1;
      }
      defined_array[i] = 999;
      /* This should initialize my int array with all the numbers
      being 3 but the last one being 999 */

      finformation = fopen("/Users/(path here)/file.txt", "w");
      /* I'm pretty sure I didn't screw up here because the file does
      get overwritten */

      i = 0;
      aux = defined_array[i];
      /* I want to read the first number in the int array 
      and store it in an int variable: aux. Here is where I've
      probably messed up things */

      while (aux != 999)
      {
          fprintf(finformation,"%d ", &aux);
          i = i+1;
          aux = defined_array[i];
      }
      /* While I don't read the last number in my int array (999), I  
      want to write the last read number into the file. Then, leave
      an space and repeat */

      fclose(finformation);
      return 0;
    }

【问题讨论】:

标签: c arrays


【解决方案1】:

删除fprintf调用中aux前面的&amp;

简单使用

fprintf(finformation, "%d ", aux);

&amp; 正在将类型形式 int 更改为 int*(指向整数的指针)。

【讨论】:

    【解决方案2】:

    从语句中删除&amp;

    fprintf(finformation,"%d ", &aux);  
                      //        ^ Remove & operator  
    

    否则程序的行为将是不确定的。

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 2012-03-04
      相关资源
      最近更新 更多