1

Possible Duplicate:
Deprecated conversion from string constant to char * error

I'm writting a program in C/C++ which is attempting to communicate over a UDP socket.

The code I'm working on has a variable, char *servIP, which is set through an input parameter to the main function. However, I want the input parameter to be optional, so I have the code:

if(argc > 1)
    servIP = argv[1];           /* First arg: server IP address (dotted quad) */
else
    servIP = "127.0.0.1";

servIP later gets converted into a more network-usable form.

When I compile this, I get a warning saying "warning: deprecated conversion from string constant to char*".

I assume this isn't the correct way to enter that IP address; what is a better way?

5
  • 1
    stackoverflow.com/questions/8126512/… has your answer Commented Oct 14, 2012 at 1:26
  • Just a note that you could eventually check if the content of argv[1] is a valid IP address. Commented Oct 14, 2012 at 1:55
  • do you realise, that your question has nothing to do with "Socket programming", "UDP".. ? Commented Oct 14, 2012 at 3:08
  • 1
    Are you programming in C or in C++? They're two different languages. Commented Oct 14, 2012 at 3:26
  • problem solution, found thanks to @Karoly Horvath, is just to do: char ip[] = "127.0.0.1"; servIP = ip; Commented Oct 14, 2012 at 6:18

1 Answer 1

4

declare servIP as a const char * instead of char * or, if that's not possible, strdup("127.0.0.1") (in the second case, just remember to free it later)

the effect of modifying a string literal is undefined, which is why c++ assigns the type "array of n const char" to a string literal. the compiler is warning you about the conversion from a const data type to a non-const one.

you can use std::string instead, and then when you need a C-style pointer to the underlying characters, you can use std::string::c_str().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.