Pointer to char array C ++
I have a problem converting the following code from c to C ++:
I have a function that accepts an array of move sequences (a sequence of characters 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 this code ok, but if I try to compile it with g ++ it gives the following warning:
main.cpp: 17: 39: warning: deprecated conversion from string constant to 'char * [-Wwrite-strings]
I believe this warning comes from the fact that a string in C is defined as char [], and C ++ uses std :: string.
So I tried to replace the code using C ++ strings like this:
void mkmove(std::string* move) {
in the mkmove defenition function and:
std::string* movestr = {'abde', "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};
in your main function and add the C ++ line 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 the task
main.cpp: In the function 'int main ():
main.cpp: 19: 39: error: scalar object' movestr requires one element in the initializer
I tried some other settings as well, but that gave me fewer compilation errors.
So what is the correct way to convert the top code from C to C ++?
Thanks for answers!
-Slovenia1337
source to share
I believe this warning comes from the fact that a string in C is defined as
char[]
, whereas C ++ usesstd::string
.
No, C string literals have a constant char[]
, while C ++ has a const char[]
.
Correct the const-correctness of your program like this:
void mkmove(const char** move) {
const char* p;
int moves[9][9];
for(int i = 0; i < 9; i++) {
for(p = move[i]; *p; p++) {
moves[i][*p - 'a'] = 3;
}
}
}
int main() {
const char* movestr[] = {"abde", "abc", "bcef", "adg", "bdefh", "cfi", "degh", "ghi", "efhi"};
mkmove(movestr);
return(0);
}
source to share