为了账号安全,请及时绑定邮箱和手机立即绑定

C ++警告:不建议将字符串常量转换为'char *'[-Wwrite-strings]

C ++警告:不建议将字符串常量转换为'char *'[-Wwrite-strings]

C++
Smart猫小萌 2019-11-19 14:34:51
我正在使用gnuplot在C ++中绘制图形。该图形正在按预期方式绘制,但是在编译过程中会出现警告。警告是什么意思?warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]这是我正在使用的功能: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);}
查看完整描述

2 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

字符串文字是const char的数组,我们可以从C ++标准草案的2.14.5 字符串文字中看到这一点,文字(强调我的):


普通字符串文字和UTF-8字符串文字也称为窄字符串文字。窄字符串文字的类型为“ n of const char数组”,其中n是下面定义的字符串的大小,并且具有静态存储持续时间(3.7)。


因此此更改将删除警告:


const char * commandsForGnuplot[] = {"set title \"Probability Graph\"", "plot     'data.temp' with lines"};

^^^^^

注意,允许* non-const char **指向const数据是一个坏主意,因为修改const或字符串文字是未定义的行为。我们可以通过转到7.1.6.1 cv-qualifiers部分看到这一点:


除了可以声明任何声明为可变的类成员(7.1.1)之外,任何在其生存期(3.8)内修改const对象的尝试都会导致未定义的行为。


和2.14.5 字符串文字部分,内容为:


是否定义了所有字符串文字(即存储在不重叠的对象中)都是实现定义的。尝试修改字符串文字的效果是不确定的。


查看完整回答
反对 回复 2019-11-19
  • 2 回答
  • 0 关注
  • 1496 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信