一、字符串指針
字符串是一種特殊的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");
- }