char s[] 和 const char s[]和char *s和const char *s 是否可以修改元素。

本文探讨了C++中字符串的比较方式,重点分析了const修饰符对字符指针和数组的影响,包括编译时与运行时的不同行为,并讨论了常成员函数与mutable关键字的相关概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include <iostream>
using namespace std;

void main()
{
 char s1[]="abc";
 char s2[]="abc";
 //cout << (s1==s2) <<endl;//0
 //s1[1]='x';//编译正确,输出axc
 //cout << s1 <<endl;
 const char s3[]="abc";
 const char s4[]="abc";
 //cout <<(s3==s4) <<endl;//0
 // s3[1]='x';//编译错误。
 char *s5="abc";
 char *s6="abc";
 //cout << (s5==s6) <<endl;//1
 //s5[1]='x';//编译通过,但运行时崩溃。
 const char *s7="abc";
 const char *s8="abc";
 cout << (s6==s7) <<endl;//1
 //cout << (s7==s8) <<endl;//1
 //s7[1]='x';//编译错误。
}
//
//继而想到常成员函数
//
//继而想到mutable关键字的作用

 

可见 加入const之后,编译就会帮你挑错。所以导致const char* 会报错,而char * 到运行才会报错。。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值