使用char指標賦值引發警告deprecated conversion from string constant to ‘char星’
阿新 • • 發佈:2018-11-09
最近在做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;
}