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?

Community
  • 1
  • 1
Gossamer Shadow
  • 387
  • 1
  • 5
  • 16

1 Answers1

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().

jspcal
  • 50,847
  • 7
  • 72
  • 76