数组和指针

区别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;
}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值