一、字符串指针
字符串是一种特殊的char型数组,指向char类型数组的指针,就是字符串指针。与普通指针一样,字符串指针在使用前也必须定义。字符串与char数组的区别在于长度,字符会自动在尾部加上一个长度‘\0’,而char型数组的长度就是其字符的个数。字符串长度是字符个数+1。例:
- #include<iostream>
- using namespace std;
- int main()
- {
- char str[]="hello world";
- char *p=str;
- cout<<str<<endl;
- cout<<p<<endl;
- cout<<*p<<endl;
- system("pause");
- }

二、char型指针数组
指针数组的元素是指针。与普通指针类似,指针数组在使用前也必须先赋值,否则可能指向没有意义的值,这是比较危险的。以char型指针数组为例。
- int main()
- {
- char *p[5]={"abc","def","ghi","jkl","mno"};
- for(int i=0;i<5;i++)
- puts(p[i]);
- system("pause");
- }

对于int型数据,如下:
- #include<iostream>
- using namespace std;
- int main()
- {
- int a=1,b=2,c=3;
- int *p[]={&a,&b,&c};//不能写成int *p[]={1,2,3},这是不合法的。因为p与[]先结合,是一个指针数组,数组的数据元素是int型指针,而不是int型数据。
- for(int i=0;i<3;i++)
- cout<<p[i]<<endl;//打印出地址(指针)
- system("pause");
- }

三、对比int型和char型数组的数组名和取地址
- #include<iostream>
- using namespace std;
- int main()
- {
- int a[]={1,2,3};
- char b[]={'a','b','c'};
- cout<<a<<endl;
- cout<<&a<<endl;
- cout<<b<<endl;
- cout<<&b<<endl;
- system("pause");
- }
