指针在c++中算是比较复杂的一部分,这篇文章主要写的是指针的的定义
*是用来定义指针
&是用来查询地址
#include<cmath>
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int a = 1000;
int *p;
p = &a;
cout<<&a<<endl;
cout<<p<<endl;
}
运行结果:
0x6ffe14
0x6ffe14
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
int a = 1001;
int *p;
p = &a;
cout<<a<<endl;
cout<<&a<<endl;
cout<<p<<endl;
return 0;
}
运行结果:
1001
0x6ffe14
0x6ffe14
我们再来看数组的地址是怎么样的
#include<cmath>
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int *p;
int b = 1;
int a[1000];
for(int i=0;i<20;i++)
{
a[i] = b;
p = &a[i];
cout<<p<<endl;
}
return 0;
}
运行结果:
0x6fee70
0x6fee74
0x6fee78
0x6fee7c
0x6fee80
0x6fee84
0x6fee88
0x6fee8c
0x6fee90
0x6fee94
0x6fee98
0x6fee9c
0x6feea0
0x6feea4
0x6feea8
0x6feeac
0x6feeb0
0x6feeb4
0x6feeb8
0x6feebc
#include<cmath>
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double *p;
double b = 1;
double a[1000];
for(int i=0;i<20;i++)
{
a[i] = b;
p = &a[i];
cout<<p<<endl;
}
return 0;
}
.
运行结果:
0x6fdec0
0x6fdec8
0x6fded0
0x6fded8
0x6fdee0
0x6fdee8
0x6fdef0
0x6fdef8
0x6fdf00
0x6fdf08
0x6fdf10
0x6fdf18
0x6fdf20
0x6fdf28
0x6fdf30
0x6fdf38
0x6fdf40
0x6fdf48
0x6fdf50
0x6fdf58
通过上面代码演示我们可以发现在一个数组中地址会根据类型大小去排列