数组和指针
来源:互联网 发布:信阳师范学院网络教学 编辑:程序博客网 时间:2024/05/01 07:33
区别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;
}
运行结果:
- 指针和指针数组
- 指针数组和数组指针
- 指针数组和数组指针
- 指针数组和数组指针
- 指针数组和数组指针
- 数组指针和指针数组
- 指针数组和数组指针
- 数组指针和指针数组
- 指针数组和数组指针
- 指针数组和数组指针
- 数组指针和指针数组
- 指针数组和数组指针
- 指针数组和数组指针
- 数组指针和指针数组
- 数组指针和指针数组
- 指针数组和数组指针
- 指针数组和数组指针
- 数组指针和指针数组
- 【BZOJ】【P1018】【SHOI2008】【堵塞的交通traffic】【题解】【线段树】
- Java线程(九):Condition-线程通信更高效的方式
- 100个熟词生义
- cmake编译简单模板形式
- BZOJ 3029 守卫者的挑战 期望DP
- 数组和指针
- Android开发环境搭建教程_eclipse篇
- webservice3
- 一种简单的UDP网络重传机制
- 大话设计模式宏观把控
- linux mint16下opencv的安装和配置
- USACO4.4.1 Shuttle Puzzle (shuttle)
- Android最佳实践之:StrictMode介绍
- [Aizu1310] Find the Multiples