【问题标题】:Cannot Convert 'char (*)[200]' to 'char**'无法将 'char (*)[200]' 转换为 'char**'
【发布时间】:2019-09-29 20:27:45
【问题描述】:
#include <iostream>
#include <string.h>

using namespace std;

void ArrayTimesThree(char*, const char*);

int main()
{
    char s1[200], s2[200], circleword[200];
    cin.getline(s1, 200);
    cin.getline(s2, 200);

    ArrayTimesThree(circleword, s1);
    cout<<circleword[1];
}

void ArrayTimesThree(char *dest[], char *source[])
{
    *dest[0] = NULL;
    strcat(*dest, *source);
    strcat(*dest, *source);
    strcat(*dest, *source);
}

main.cpp|21|错误:无法将参数 '1' 的 'char (*)[200]' 转换为 'char**' 到 'void ArrayTimesThree(char**, char**)'

【问题讨论】:

    标签: c++ arrays function compiler-errors


    【解决方案1】:

    您正在向 ArrayTimesThree 传递一个 char*,但是,在方法签名中您告诉它期待一个 char**。不要忘记使用[] 运算符算作取消引用。试试这个:

    #include <iostream>
    #include <string.h>
    
    using namespace std;
    
    void ArrayTimesThree(char*, char*);
    
    int main()
    {
        char s1[200], s2[200], circleword[200];
        cin.getline(s1, 200);
        cin.getline(s2, 200);
    
        ArrayTimesThree(circleword, s1);
        cout<<circleword[1];
    
        return 0;
    }
    
    void ArrayTimesThree(char *dest, char source[])
    {
        dest[0] = '\0';
        strcat(dest, source);
        strcat(dest, source);
        strcat(dest, source);
    }
    

    免责声明:我不确定您对这段代码的期望是什么,所以我不能保证逻辑是正确的;但是,这将解决您的编译器错误,并且似乎可以正常运行代码的编写方式。

    【讨论】:

      【解决方案2】:

      问题实际上只是因为您最初的 声明 ArrayTimesThree(这是“正确的”)与 不匹配您稍后给出的定义(实际上这是错误的)。如下更改您的定义,它可以工作:

      void ArrayTimesThree(char* dest, const char* source) // Needs to be the same as in the previous declaration!
      {
          dest[0] = '\0';   // Don't assign a string pointer to NULL! Instead, set its first character to the nul character
      //  strcpy(dest, ""); // ALternatively, use strcpy with an empty string to clear "dest"
          strcat(dest, source); // strcat takes char* and const char* arguments ...
          strcat(dest, source); // ... so there is no need to 'deference the values ...
          strcat(dest, source); // ... now that the argument types have been 'corrected'
      }
      

      顺便说一句,我注意到 s2 在您的 main 函数中的输入值从未实际使用过……这就是您现在想要的吗?

      【讨论】:

      • 是的,当我看到它在那个阶段工作后,我打算完成它:)。因此,据我了解,您不应该将函数的参数作为“指向数组的指针”,就像我所做的那样。你应该只放一个指向变量类型的指针,对吧?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多