Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to char array C++

I have problem converting next code from c to c++:
I have a function that takes an array of move sequences (sequence of chars from a to i) as arg.

code:

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);
}

gcc compiles that code fine, but if I try to compile it with g++ it gives me next warning:
main.cpp:17:39: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

I believe this warning comes from the fact that string in C is defined as char[], while c++ uses std::string.
So I tried replacing the code to use C++ strings like this:

void mkmove(std::string* move) {

in mkmove function defenition, and:

std::string* movestr = {'abde', "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};

in main function and add the C++ string header file:

#include <string>

but now I get errors:
main.cpp: In function ‘void mkmove(std::string*)’:
main.cpp:11:21: error: cannot convert ‘std::string {aka std::basic_string}’ to ‘char*’ in assignment
main.cpp: In function ‘int main()’:
main.cpp:19:39: error: scalar object ‘movestr’ requires one element in initializer

I also tried some other tweaks but that gave me least errors on compile.

So what is proper way to convert top code from C to C++?

Thanks for answers!

-Slovenia1337

like image 541
David Gricar Avatar asked May 10 '26 08:05

David Gricar


2 Answers

use

std::string movestr[] = {"abde", "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};
like image 74
enobayram Avatar answered May 11 '26 20:05

enobayram


No, the warning isn't because you should use string, it's because character strings are read-only.

Either declare strings as char ...[] or as const char *.

In your case, you're declaring an array of char *, which is a deprecated feature (converting from const char * to char *.

like image 41
Mahmoud Al-Qudsi Avatar answered May 11 '26 20:05

Mahmoud Al-Qudsi