指向char数组C++的指针

Dav*_*car 3 c c++ arrays pointers

我有问题将下一个代码从c转换为c ++:
我有一个函数,它将一个移动序列数组(字符序列从a到i)作为arg.

码:

void mkmove(char** move) {
    int i = 0;
    char* p = NULL;
    int moves[9][9];

    for(int i = 0; i < 9; i++) {
        for(p = move[i]; *p; p++) {
            moves[i][*p - 'a'] = 3;
        }
    }
}

int main() {
    char* movestr[] = {"abde", "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};
    mkmove(movestr);

    return(0);
}
Run Code Online (Sandbox Code Playgroud)

gcc编译该代码很好,但如果我尝试用g ++编译它,它会给我下一个警告:
main.cpp:17:39:警告:不推荐将字符串常量转换为'char*'[-Wwrite-strings]

我相信这个警告来自C中的字符串定义为char [],而c ++使用std :: string.
所以我尝试将代码替换为使用C++字符串,如下所示:

void mkmove(std::string* move) {
Run Code Online (Sandbox Code Playgroud)

在mkmove函数defenition中,和:

std::string* movestr = {'abde', "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};
Run Code Online (Sandbox Code Playgroud)

在main函数中添加C++字符串头文件:

#include <string>
Run Code Online (Sandbox Code Playgroud)

但现在我得到错误:
main.cpp:在函数'void mkmove(std :: string*)':
main.cpp:11:21:错误:无法将'std :: string {aka std :: basic_string}'转换为赋值
main.cpp中的'char*' :在函数'int main()'中:
main.cpp:19:39:错误:标量对象'movestr'在初始化程序中需要一个元素

我也尝试了一些其他的调整,但这给了我最少的编译错误.

那么将顶级代码从C转换为C++的正确方法是什么?

谢谢你的回答!

-Slovenia1337

eno*_*ram 5

使用

std::string movestr[] = {"abde", "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};
Run Code Online (Sandbox Code Playgroud)


Mah*_*dsi 5

不,警告不是因为你应该使用string,这是因为字符串是只读的.

将字符串声明为char ...[]或作为const char *.

在您的情况下,您将声明一个数组char *,这是一个不推荐使用的功能(从转换const char *char *.