johnny94
johnny94

Reputation: 321

Is possible to convert argument from 'const char []' to 'char *' in C++?

Definition of method is:

void setArgument(char *);

And i call that method with this code:

setArgument("argument");

But my VisualStudio compiler gets me the next error:

cannot convert argument 1 from 'const char [10]' to 'char *'

Is it possible to send arguments like this or I must change arguments type in the method? Also, VS show me next note in output: note: Conversion from string literal loses const qualifier (see /Zc:strictStrings)

Upvotes: 0

Views: 1771

Answers (2)

bobah
bobah

Reputation: 18864

It's possible, just if you really need the argument to be mutable (char* and not char const*), you need to allocate a new storage in the mutable memory and clone the contents of the constant memory to there, if that fits into your definition of "convert".

auto const len = strlen(input);
auto const buf = std::unique_ptr<char[]>(new char[len + 1]);
memcpy(buf, input, len + 1);

If you actually need char const* and if you are C++17 or later, you can possibly change the signature to setArgument(std::string_view arg), making it misuse-proof.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

The problem is that string literals are arrays of constant characters.

While the array could easily decay to a pointer to its first element, the type of that pointer is const char *. Which needs to be the type of the argument for your functions.

And if you need to modify the string you pass, then you should create your own non-constant array:

char argument[] = "argument";
setArgument(argument);

Of course, since you're programming in C++ you should stop using char pointers and arrays and instead use std::string.

Upvotes: 3

Related Questions