使用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;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值