hmb
hmb

Reputation: 103

how initialize char* const argv [] in c++

An API function takes an argument of type 'char *const argv[]' I am initializing this type of arguments in my c++ application like:

char* const  argv[] = {"--timeout=0", NULL}; 

and passing the arguments to API function like:

Spawner spawner;
spawner.execute (argv, true);

using g++ compiler, I am getting following Error:

error: deprecated conversion from string constant to 'char*' [-Werror=write-strings]

how can I get rid of above error?

Below is the declaration of execute function in API:

void Spawner::execute (char *const argv[], bool bShowChildWindow)

Upvotes: 3

Views: 2821

Answers (3)

R Sahu
R Sahu

Reputation: 206607

char* const  argv[] = {"--timeout=0", NULL}; 

declares argv to be a array of const pointers to char. It is not a pointer to const char.

You can see the error in a simpler statement:

char* s = "foo";

That can be fixed by using one of the following:

char const* s = "foo";  // Points to the read-only memory
char* s[] = "foo";      // Makes a copy of the read-only memory

What you need for argv is one of the following:

char argv1[][50] = {"--timeout=0"}; 
char* argv[] = {argv1[0], NULL}; 

or

char argv1[] = "--timeout=0"; 
char* argv[] = {argv1, NULL}; 

and pass argv to Spawner::execute.

If you don't want the compiler to produce an error with these, you can use -Wno-write-strings. But then, if you do that, you will be treading on thin ice. You could end up modifying the read only memory by accident and cause undefined behavior.

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180236

Aside from disabling -Werror for the underlying warning, or disabling the warning altogether, you could do this:

char arg0[] = "--timeout=0";
char* const  argv[] = {arg0, NULL};

In that case, the string serves as an array initializer; no pointer to it is ever involved.

Upvotes: 4

user3386109
user3386109

Reputation: 34829

Yeah, C++ is annoyingly (but correctly) strict about const chars. Try this

char timeoutString[] = "--timeout=0";    // make a non-const char array
char *argv[] = { timeoutString, NULL };
Spawner spawner;
spawner.execute( argv, true );

Technically, the problem is with the declaration of the execute method, which should be

void Spawner::execute (const char *const argv[], bool bShowChildWindow)

assuming execute doesn't modify the strings or the array.

Upvotes: 4

Related Questions