分类程序的错误代码难以理解

时间:2018-07-26 16:41:27

标签: c++ arrays sorting multidimensional-array

我用c ++编写了一个程序,该程序应该打印一个单词中某个字母包含多少次。因此,我使用了2D数组,这对我来说是一个新东西,我得到3个我不太了解的错误代码。感谢您的帮助!

#include <iostream>
#include <cstring>

void check(char wArr[], int letter[], char search[], std::string word);

int main(int argc, char const *argv[]) {
        //int letter[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        char search[26][2] = {{'a', 0},{'b', 0},{'c', 0},{'d', 0},{'e', 0},{'f', 0},{'g', 0},{'h', 0} ,{'i', 0} ,
        {'j', 0},{'k', 0},{'l', 0},{'m',0} ,{'n',0} ,{'o',0},{'p',0},{'q',0},{'r',0},{'s',0},{'t',0},
        {'u', 0},{'v', 0} ,{'w',0},{'x',0},{'y', 0},{'z', 0}};
        std::string word;
        std::cout << "Please enter the word: \n";
        std::cin >> word;
        char wArr[word.length()];
        strcpy (wArr, word.c_str ());
        check(wArr, search, word);

        return 0;
}

void check(char wArr, char search[][2], std::string word){
        for(int s = 0; s < 26; s++) {
                for ( char i = 0; i < word.length(); i++) {
                        if(wArr[i] == search[s][1]) {
                                search[s][2]++;
                        }
                }
        }
        for (int t = 0; t < 26; t++) {
                if(search[t][2] > 0){
                  std::cout << search[t][1] << ": " << search[t][2] << '\n';
        }
      }
}

错误代码:

/home/julian/workspace-atom/countletter/main.cpp: In function ‘int main(int, const char**)’:
/home/julian/workspace-atom/countletter/main.cpp:16:33: error: cannot convert ‘char (*)[2]’ to ‘int*’ for argument ‘2’ to ‘void check(char*, int*, char*, std::__cxx11::string)’
         check(wArr, search, word);
                                 ^
/home/julian/workspace-atom/countletter/main.cpp: In function ‘void check(char, char (*)[2], std::__cxx11::string)’:
/home/julian/workspace-atom/countletter/main.cpp:24:34: error: invalid types ‘char[char]’ for array subscript
                         if(wArr[i] == search[s][1]) {
                                  ^

1 个答案:

答案 0 :(得分:0)

错误非常明显。与实际定义相比,您的函数原型具有不同的参数类型:

void check(char wArr[], int letter[], char search[], std::string word);

vs

void check(char wArr, char search[][2], std::string word)

第二个错误是由于在将wArr声明为char时尝试使用{{1}}作为数组。