使用char指针赋值引发警告deprecated conversion from string constant to ‘char星’

版权声明:转载请注明出处。作者:两仪织,博客地址:http://blog.csdn.net/u013894427 https://blog.csdn.net/u013894427/article/details/83782091

最近在做demo的时候遇到如下警告。

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

参考代码为:

#include <stdio.h>
#include <string>

using namespace std;

int main(){
   char *x="hello x";
   string z;
   z=x;
   printf("z=%s\n",z.c_str());	
   return 0;
}

查了资料之后发现这个问题是因为char *背后的含义是:给我个字符串,我要修改它

但是char*赋值给string是不应该被修改的。所以才会出现这个警告

解决这个问题的方法有两种

方法一:设置char*为常量加上const

#include <stdio.h>
#include <string>

using namespace std;

int main(){
	const char *x="hello x";
	string z;
	z=x;
	printf("z=%s\n",z.c_str());	
	return 0;
}

方法二:改用char[]来进行操作

#include <stdio.h>
#include <string>

using namespace std;

int main(){
   char x[]="hello x";
   string z;
   z=x;
   printf("z=%s\n",z.c_str());	
   return 0;
}

猜你喜欢

转载自blog.csdn.net/u013894427/article/details/83782091