C++ 编译器说并没有声明变量,但它是在前一行声明的

C++ 编译器说并没有声明变量,但它是在前一行声明的,c++,C++,我使用MingW作为我的编译器。我已经声明了一个变量strl,但是它说它没有在它下面的行声明 struct idstruct { char * path; lua_State **state; }; idstruct ids[] = {}; int nids = 0; static char* getPath(lua_State **state) { std::cout << state; for (int on = 0; on < nids; on

我使用MingW作为我的编译器。我已经声明了一个变量strl,但是它说它没有在它下面的行声明

struct idstruct {
    char * path;
    lua_State **state;
};

idstruct ids[] = {};
int nids = 0;

static char* getPath(lua_State **state) {
  std::cout << state;
  for (int on = 0; on < nids; on++)
    idstruct strl = ids[on];
    if (strl.state == state) {
      return strl.path;
    }
  }
}

在for循环体的开头缺少一个卷曲括号。当您到达下面的if语句时,strl已经超出了范围。

您在for循环中遗漏了一个括号,因此它只是一行,尽管有缩进。因此,该变量不在其下面的if语句的范围内

试试这个:

  for (int on = 0; on < nids; on++) {  // add a brace here
    idstruct strl = ids[on];
    if (strl.state == state) {
      return strl.path;
    }
  }  // and here

零长度数组是非法的。如果零长度数组刚开始编译时使用任何索引对其进行索引也是非法的。在你职业生涯的这个阶段,编译器比你更可能是正确的。这种情况甚至发生在您编写了十年、二十年或三年的程序之后,尽管通常您会觉得编译器在几年后出错的频率会降低。