| Message |
Well it isn't really valid to coerce "const char *" to "char *", particularly with string literals. For one thing, once it becomes char *, and pass it to a function, that function can validly change it. Now for a literal, which is likely to be shared amongst various places, this might result in changing "dog" to "cat" not just once, but everywhere in the program.
Another problem is that literals are likely to be in protected memory, so it will crash if you attempt to change it.
Basically, what you need to do is, if you are passing a literal down to a function, that function should be taking a const char * argument, not a char * argument.
However this can be fiddly to get right, as you then find that if this function calls other functions, they also need to be changed and you get a knock-on effect. Plus, sometimes you actually want to pass down char * data (eg. something the player types), so making it take the const form can then break other things.
If you are using C++ and not C, you might be able to use the string class to work around this. For example, instead of:
void my_func (char * s) { blah }
you might have:
void my_func (string s) { blah }
For example:
#include <iostream>
#include <string>
using namespace std;
void my_func (char * s)
{
cout << s << endl;
}
int main (void)
{
my_func ("nick");
return 0;
}
Compiles with:
test1.cpp: In function ‘int main()’:
test1.cpp:14: warning: deprecated conversion from string constant to ‘char*’
However:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
void my_func (string s)
{
cout << s << endl;
}
int main (void)
{
char s1 [] = "hello there";
char s2 [100];
strcpy (s2, "testing");
my_func ("nick");
my_func (s1);
my_func (s2);
return 0;
}
That compiled without warnings, and printed all 3 strings. Once you have a string (as in, the string class) you can convert back to const char * with the c_str function. For example:
string s3 = "test";
printf ("%s\n", s3.c_str ());
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|