使用char指針賦值引發警告deprecated conversion from string constant to ‘char星’

最近在做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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章