hongqiang 发表于 2013-2-4 22:11:53

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

一、字符串指针
字符串是一种特殊的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");    }
http://my.csdn.net/uploads/201208/19/1345385795_8641.jpg



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

int main(){    char *p={"abc","def","ghi","jkl","mno"};    for(int i=0;i<5;i++)    puts(p);    system("pause");    }
http://my.csdn.net/uploads/201208/19/1345386584_5426.jpg对于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},这是不合法的。   for(int i=0;i<3;i++)   cout<<p<<endl;//打印出地址(指针)      system("pause");    }
http://my.csdn.net/uploads/201208/19/1345388132_2522.jpg



三、对比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");    }
http://my.csdn.net/uploads/201208/19/1345386776_6638.jpg

更多详细信息请查看java教程网 http://www.itchm.com/forum-59-1.html
页: [1]
查看完整版本: 字符串指针与char型指针数组