问题
I am using gnuplot to draw a graph in C++. The graph is being plot as expected but there is a warning during compilation. What does the warning mean?
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
This is the function I am using:
void plotgraph(double xvals[],double yvals[], int NUM_POINTS)
{
char * commandsForGnuplot[] = {\"set title \\\"Probability Graph\\\"\",
\"plot \'data.temp\' with lines\"};
FILE * temp = fopen(\"data.temp\", \"w\");
FILE * gnuplotPipe = popen (\"gnuplot -persistent \", \"w\");
int i;
for (i=0; i < NUM_POINTS; i++)
{
fprintf(temp, \"%lf %lf \\n\", xvals[i], yvals[i]);
//Write the data to a te mporary file
}
for (i=0; i < NUM_COMMANDS; i++)
{
fprintf(gnuplotPipe, \"%s \\n\", commandsForGnuplot[i]);
//Send commands to gn uplot one by one.
}
fflush(gnuplotPipe);
}
回答1:
String literals are an array of const char, we can see this from the draft C++ standard section 2.14.5
String literals which says (emphasis mine):
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).
so this change will remove the warning:
const char * commandsForGnuplot[] = {"set title \"Probability Graph\"", "plot 'data.temp' with lines"};
^^^^^
Note, allowing a *non-const char** to point to const data is a bad idea since modifying a const or a string literal is undefined behavior. We can see this by going to section 7.1.6.1
The cv-qualifiers which says:
Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
and section 2.14.5
String literals which says:
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.
来源:https://stackoverflow.com/questions/21529194/c-warning-deprecated-conversion-from-string-constant-to-char-wwrite-stri