【问题标题】:Error: ‘fp’ is used uninitialized in this function [-Werror=uninitialized] [closed]错误:在此函数中未初始化使用“fp”[-Werror=uninitialized] [关闭]
【发布时间】:2021-11-11 23:29:27
【问题描述】:

我对在 C 中使用文件比较陌生。今天,当我在编写程序时,当我声明一个 FILE 指针并尝试使用它时, 我不断收到此错误:

answer3.c:44:5: error: ‘fp’ is used uninitialized in this function [-Werror=uninitialized]
   if(fp == NULL)
     ^
cc1: all warnings being treated as errors

这是我的代码

bool  runIntegrate(char * infilename, char * outfilename)
    // return true if it can successfully open and read the input 
    // and open and write the output
    // return false when encountering any problem
    {
      Integration intrg;
      FILE * fp;
      fopen(infilename,"r");
      // open the input file name for reading
      // if fopen fails, return false
      if(fp == NULL)
       {
        fclose(fp);
        return false;            
       }
      
      if (fscanf(fp,"%lf\n", &intrg.lowerlimit) != 1){
        fclose(fp);
        return false;
      }

我很确定我的格式正确,所以我不太确定问题出在哪里。任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你不明白什么?你在哪里给fp赋值?我认为您的意思是将fopen() 的结果分配给它。
  • fp = fopen(infilename,"r");
  • 错误信息很清楚。您尚未为 fp* before you use it in your if` 语句赋值。 formatting 无关紧要 - 您可以将代码编写为没有任何格式的单行,但您仍然不会为 fp 分配值。

标签: c file pointers initialization variable-assignment


【解决方案1】:

你忘了把函数fopen调用的返回值赋给指针fp

  FILE * fp;
  fopen(infilename,"r");
  // open the input file name for reading
  // if fopen fails, return false
  if(fp == NULL)
  //...

因此指针fp 保持未初始化状态。

改为写

  FILE * fp = fopen(infilename,"r");
  // open the input file name for reading
  // if fopen fails, return false
  if(fp == NULL)

注意,函数参数最好用限定符const声明,因为它们不会在函数内改变

bool  runIntegrate( const char * infilename, const char * outfilename)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    相关资源
    最近更新 更多