无法识别全局变量

时间:2020-01-17 01:10:29

标签: c++ global-variables global

我编写了一个函数,该函数接收一个浮点数组x并执行一些 操作。该数组的维数由数字给出 文件中的行数。为了使这个过程自动化,我写了一个 读取文件并返回行数的函数。

 int dim(){
 unsigned int number_of_lines = 0;
 FILE *file = fopen("prod.txt", "r");
 int ch;

 while (EOF != (ch=getc(file)))
     if ('\n' == ch)
         ++number_of_lines;

 return number_of_lines;
 }

然后,我将此值声明为全局变量:

 const int numofdims = dim();

但是,当我在cost中调用函数main时(初始化数组x[numofdims]之后)

 float cost(x[numofdims]){
     int i,j;
     float v = 0;
     vector<float x_in;
     vector<float x_origin;
     for(i=0;i<numofdims;i++){
         x_origin.push_back(x[i]);
         x_in.push_back(x[i]);
    // does several calculations
    // ...
      return v;
 }

 int main(){

  float x[46] = {1.92215242,   6.27128854,   9.53873027,  14.79595426,
     18.92807696,  25.85703415,  29.93216819,  33.84737516,
     42.19055   ,  48.81144008,  60.99963933,  63.34494338,
     67.69622093,  73.07859412,  80.46676915,  85.10451921,
     87.49178446,  92.34202212,  96.37983996,  98.90903662,
    101.99359444, 106.88409251, 113.81421998, 120.42050161,
    124.43256197, 126.96629951, 133.88193576, 139.48952166,
    149.57054363, 155.55769723, 159.66096967, 167.09857013,
    173.4584723 , 176.70360324, 181.43200013, 182.80392359,
    185.65336252, 187.64028963, 191.06631673, 193.69478216,
    198.94720133, 202.68384665, 209.7697676 , 212.26092809,
    219.06840905, 221.61314655};
 printf("%d", numofdims);
 float v = cost(x);
 }

我得到了错误

 array bound is not an integer constant before ‘]’ token
 float cost(float x[numofdims]){

 array_param.cpp: In function ‘float cost(...)’:
 array_param.cpp:232:28: error: ‘x’ was not declared in this scope
      x_origin.push_back(x[i]);

但是,如果我不是将dim()赋予变量numofdims,而是这样做

 const int numofdims = 46;

其中46是我要读取的文件之一的行数, 该功能完全按照我的预期工作。在两种情况下 numfodims的声明(使用dim()或数字属性), 当我打印时

 printf("%d", numofdims);

我获得值46。为什么会发生这种情况,以及如何防止 它吗?

0 个答案:

没有答案