string,char,char*,char a[] 占字节数, 以及sizeof,strlen(),str.length()的用法

来源:互联网 发布:java ssh项目 编辑:程序博客网 时间:2024/04/25 04:35
  1. // studystring.cpp :    
  2. //   
  3.   
  4. #include "stdafx.h"   
  5. #include <iostream>   
  6. #include <string>   
  7. using namespace std;  
  8.   
  9. int main(int argc, char* argv[])  
  10. {  
  11.       
  12.     cout<<"char,char*,string 在C++中的占几个字节: -------------------------"<<endl;  
  13.     cout<<"sizeof(char) = "<<sizeof(char)<<endl; //=1  
  14.     cout<<"sizeof(char*) = "<<sizeof(char*)<<endl; //=4  
  15.     cout<<"sizeof(string) = "<<sizeof(string)<<endl; //=16  
  16.     cout<<"----------------------------------------------------------------"<<endl;  
  17.     cout<<endl;cout<<endl;  
  18.   
  19.     string str;  
  20.     str = "12345678912"// 11个字符  
  21.     cout<<"the size of str = "<<sizeof(str)<<endl; // = 16  
  22.     cout<<"the length of str = "<<str.length()<<endl;// = 11   
  23.     cout<<"----------------------------------------------------------------"<<endl;  
  24.     cout<<endl;cout<<endl;  
  25.        
  26.     //--   
  27.     char* ch = "12345678912"// 11个字符       
  28.     cout<<"the size of ch = "<<sizeof(ch)<<endl; // = 4  
  29.     cout<<"the length of ch = "<<strlen(ch)<<endl;// = 11   
  30.     cout<<"----------------------------------------------------------------"<<endl;  
  31.     cout<<endl;cout<<endl;  
  32.   
  33.     //--   
  34.   
  35.     char a[]="12345678912"// 11个字符      
  36.     cout<<"the size of a = "<<sizeof(a)<<endl; // = 12,包括了字符串结束符'\0'  
  37.     cout<<"the length of a = "<<strlen(a)<<endl; //=11  
  38.     cout<<"----------------------------------------------------------------"<<endl;  
  39.     cout<<endl;cout<<endl;  
  40.   
  41.     //--   
  42.     char chr[12]="12345678912"// 11个字符     char chr[11]="12345678912"; 编译报错 array bounds overflow  
  43.     cout<<"the size of chr = "<<sizeof(chr)<<endl; // =12  
  44.     cout<<"the length of chr = "<<strlen(chr)<<endl; // =11  
  45.     cout<<"----------------------------------------------------------------"<<endl;  
  46.     cout<<endl;cout<<endl;  
  47.   
  48.     //--   
  49.     char chrr[100]="12345678912"// 11个字符    
  50.     cout<<"the size of chrr = "<<sizeof(chrr)<<endl; // =100  
  51.     cout<<"the length of chrr = "<<strlen(chrr)<<endl; // =11  
  52.     cout<<"----------------------------------------------------------------"<<endl;  
  53.     cout<<endl;cout<<endl;  
  54.   
  55.     //--   
  56.     char strr[8]={'a'};  
  57.     cout<<"the size of strr = "<<sizeof(strr)<<endl; // =8  
  58.     cout<<"the length of strr = "<<strlen(strr)<<endl; // =1  
  59.     cout<<"----------------------------------------------------------------"<<endl;  
  60.     cout<<endl;cout<<endl;  
  61.   
  62.     return 0;  
  63. }  
原创粉丝点击