错误:在']'标记之前预期的primary-expression

时间:2013-08-24 15:49:18

标签: c++ arrays

我收到了错误:

  

在'''令牌'之前预期的主要表达

在这一行:

berakna_histogram_abs(histogram[], textRad);

有人知道为什么吗?

const int ANTAL_BOKSTAVER = 26;  //A-Z

void berakna_histogram_abs(int histogram[], int antal);

int main() {

   string textRad = "";
   int histogram[ANTAL_BOKSTAVER];

   getline(cin, textRad);

   berakna_histogram_abs(histogram[], textRad);
   return 0;
}

void berakna_histogram_abs(int tal[], string textRad){

   int antal = textRad.length();

   for(int i = 0; i < antal; i++){

      if(textRad.at(i) == 'a' || textRad.at(i) == 'A'){
        tal[0] + 1;
      }
   } 
}

4 个答案:

答案 0 :(得分:3)

在main()中调用函数是错误的:

berakna_histogram_abs(histogram[], textRad);

应该是:

berakna_histogram_abs(histogram, textRad);

仅在函数声明中需要[]但在调用函数时不需要{{1}}。

答案 1 :(得分:3)

berakna_histogram_absmain()函数的调用有误,应该是:

berakna_histogram_abs(histogram, textRad);
//                             ^

[]在函数声明中表示它需要一个数组,你不必将它用于函数调用。

您还有其他错误:

函数berakna_histogram_abs的原型是:

void berakna_histogram_abs(int histogram[], int antal);
//                                          ^^^
main()定义和

之前

void berakna_histogram_abs(int tal[], string textRad){...}
//                                    ^^^^^^

同样在你的主要部分,你试图传递一个字符串作为参数,所以你的代码应该是:

void berakna_histogram_abs(int histogram[], string antal);

int main()
{
    // ...
}

void berakna_histogram_abs(int tal[], string textRad){
    //....
}

最后一件事:尝试传递引用或const引用而不是值:

void berakna_histogram_abs(int tal[], string& textRad)
//                                          ^

您的最终代码应如下所示:

const int ANTAL_BOKSTAVER = 26;  //A-Z

void berakna_histogram_abs(int histogram[], const string& antal);

int main() {

   string textRad = "";
   int histogram[ANTAL_BOKSTAVER];

   getline(cin, textRad);

   berakna_histogram_abs(histogram, textRad);
   return 0;
}

void berakna_histogram_abs(int tal[], const string& textRad) {

   int antal = textRad.length();

   for(int i = 0; i < antal; i++){

      if(textRad.at(i) == 'a' || textRad.at(i) == 'A'){
        tal[0] + 1;
      }
   } 
}

答案 2 :(得分:2)

您正在将表传递给函数错误。你应该简单地说:

berakna_histogram_abs(histogram, textRad);

你首先要宣布的是:

void berakna_histogram_abs(int histogram[], int antal);

但是你要试图定义:

void berakna_histogram_abs(int tal[], string textRad){}

这是你的编译器认为第二个参数是int而不是string的方式。功能原型应与声明一致。

答案 3 :(得分:0)

错误正在传递histogram[]
只通过histogram 在参数中,您已将第二个参数定义为int,但在定义函数时,您将第二个参数保留为string类型
    改变初始定义

void berakna_histogram_abs(int histogram[], int antal);

void berakna_histogram_abs(int histogram[], string textRad);