In my code I have
char* s = strchr(first,'/');
if(s==NULL) s = "";
else s = s+1;
But my gcc compiler complains at the penultimate line with
warning: assignment discards qualifiers from pointer target type
From what I understand about ANSI C, it is because I am setting s (a non-const value) to a string literal (a const value). (Am I wrong here?) Yet I need s to be non-const (because I may be changing its value by adding 1 to it), and I also need to set s to an empty string literal. Do I have any options in terms of better code design here to achieve these two objectives without the compiler yelling?
I do have the -Wwrite-strings flag enabled.
You should use
strcpyinstead of assigning string literals. The problem is that the string literal is constant, andswill contain the address of that string, not the string itself, which is bad.For example if you have:
The address of the 100 char’s allocated will be replaced with the address of
"Hello world"constant string.Easiest way to make a string empty is to set the first value to NULL (
*s = NULL);