Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

C++ warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

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 
", xvals[i], yvals[i]); 
        //Write the data to a te  mporary file
    }
    for (i=0; i < NUM_COMMANDS; i++)
    {
        fprintf(gnuplotPipe, "%s 
", commandsForGnuplot[i]); 
        //Send commands to gn  uplot one by one.
    }
    fflush(gnuplotPipe);
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...