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

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

你可能感兴趣的:(c基础)