玩一玩字符串指针

gcc版本  8.2.0   Linux  centos 7

 

输出字符串数组中的每个值

发现——字符串末尾的\0是真实存在的

  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main(){
  5     char str[]="hello";
  7     for(auto i :str){
  8         cout<<i<<endl;
  9     }
 10     printf("%s \n",str);
 11     return 0;
 12 }

字符串最后的\0也被输出了。

 

 

修改字符串数组str索引位置为0的地址上的值

故意写的超过一个字符,最后报错——段错误

  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main(){
  5     char str[]="hello";
  6     scanf("%s", str[0]);
  7     printf("%s \n",str);
  8     return 0;
  9 }

 

 

修改字符串str上的值

故意写的很长,有的版本会把str3里面的值也都改成aaaaaaa了,我这个版本报错——段错误(不同版本还是有差异的)

  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main(){
  5     char str[]="hello";
  6     char str3[]="abcdeftg";
  7     cout<<"str3="<<str3<<endl;
  8     scanf("%s", str);
  9     printf("str=%s \n",str);
 10     cout<<"str3="<<endl;
 11     return 0;
 12 }

 

如果str3没有被赋初值

  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main(){
  5     char str[]="hello";
  6     char str3[10];
  7     scanf("%s", str);
  8     printf("str=%s \n",str);
  9     cout<<"str3="<<endl;
 10     return 0;
 11 }

 

修改str的值

这次我只传入了一个a,然后打印连续地址上的值,发现hello中的“he”被覆盖了,后面的“llo”还活着

  1 #include<iostream>
  2 using namespace std;
  3 
  4 int main(){
  5     char str[]="hello";
  6     char str3[10];
  7     scanf("%s", str);
  8     printf("str=%s \n",str);
  9     cout<<"str3="<<endl;
 10     for(int i=0; i<15;i++){
 11         cout<<str[i]<<endl;
 12     }
 13     return 0;
 14 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值