天天看點

玩一玩字元串指針

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 }           
玩一玩字元串指針

繼續閱讀