字符串指针与char型指针数组

来源:互联网 发布:肌研极润怎么样知乎 编辑:程序博客网 时间:2024/06/01 14:42

一、字符串指针

字符串是一种特殊的char型数组,指向char类型数组的指针,就是字符串指针。与普通指针一样,字符串指针在使用前也必须定义。字符串与char数组的区别在于长度,字符会自动在尾部加上一个长度‘\0’,而char型数组的长度就是其字符的个数。字符串长度是字符个数+1。例:

[cpp] view plaincopyprint?
  1. #include<iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.     char str[]="hello world";  
  6.     char *p=str;  
  7.     cout<<str<<endl;  
  8.     cout<<p<<endl;  
  9.     cout<<*p<<endl;  
  10.     system("pause");  
  11.     }  



二、char型指针数组

指针数组的元素是指针。与普通指针类似,指针数组在使用前也必须先赋值,否则可能指向没有意义的值,这是比较危险的。以char型指针数组为例。

[cpp] view plaincopyprint?
  1. int main()  
  2. {  
  3.     char *p[5]={"abc","def","ghi","jkl","mno"};  
  4.     for(int i=0;i<5;i++)  
  5.     puts(p[i]);  
  6.     system("pause");  
  7.     }  

对于int型数据,如下:

[cpp] view plaincopyprint?
  1. #include<iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.     int a=1,b=2,c=3;  
  6.     int *p[]={&a,&b,&c};//不能写成int *p[]={1,2,3},这是不合法的。因为p与[]先结合,是一个指针数组,数组的数据元素是int型指针,而不是int型数据。   
  7.     for(int i=0;i<3;i++)  
  8.      cout<<p[i]<<endl;//打印出地址(指针)   
  9.      system("pause");  
  10.     }  



三、对比int型和char型数组的数组名和取地址

[cpp] view plaincopyprint?
  1. #include<iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     int a[]={1,2,3};  
  7.     char b[]={'a','b','c'};  
  8.     cout<<a<<endl;  
  9.     cout<<&a<<endl;  
  10.     cout<<b<<endl;  
  11.     cout<<&b<<endl;  
  12.     system("pause");  
  13.     }  

0 0
原创粉丝点击