区别1:
指针和数组区别:
int a[]={1,2,3,4,5};
int *p=a;
sizeof(a);//结果为20
sizeof(p);//结果为4
另外,如果数组作为函数形参,则退化为指针。因此
void fun(int a[]){sizeof(a);}//结果为4
区别2:
#include<iostream>
using namespace std;int main(){
char a1[] = "hello";
char a2[] = "hello";
char *p1 = "hello";
char *p2 = "hello";
/*a1和a2的初始地址不同的数组,分别分配了能够
存储字符串的内存空间。
*/
if (a1 == a2)
cout << "a1 is same as a2" << endl;
else
cout << "a1 is not same as a2" << endl;
/*C/C++中把常量字符串放到单独的一个内存区域,
所以p1和p2无须分配内存以存储内容,而只需要指
向常量字符串的内存地址即可。因此p1和p2是相同的。
*/
if (p1==p2)
cout << "p1 is same as p2" << endl;
else
cout << "p1 is not same as p2" << endl;
return 0;
}
另外一个测试:说明直接用“==”判断是否与常量字符串比较,指针可以,数组不可以。
#include<iostream>
using namespace std;
int main(){
char *p="hello";
char s[]="hello";
if(p=="hello") cout<<"p is the same with hello"<<endl;
else cout<<"p is not the same with hello"<<endl;
if(s=="hello") cout<<"s is the same with hello"<<endl;
else cout<<"s is not the same with hello"<<endl;
return 0;
}
测试结果:
这个时候应该用strcmp()函数:
#include<iostream>
#include"string.h"
using namespace std;
int main(){
char *p="hello";
char s[]="hello";
if(strcmp(p,"hello")==0) cout<<"p is the same"<<endl;
else cout<<"p is not the same"<<endl;
if(strcmp(s,"hello")==0) cout<<"s is the same"<<endl;
else cout<<"s is not the same"<<endl;
return 0;
}
运行结果: