什么是指针?
指针就是一个变量
指针干啥的?
指针变量的值为另一个变量的地址
在了解指针之前,你需要了解一下&(连字号)运算符访问地址,表示在内存中访问地址
举个例子
#include<iostream>
using namespace std;
int main()
{
int var1=1;
int var2[20];
cout<<"The value of var1 varaible\t";
cout<<var1<<endl;
cout<<"The Address of var1 varaible\t";
cout<<&var1<<endl;
cout<<"The value of var2 varaible\t";
cout<<&var2[0]<<endl;
cout<<"The value of var2 varaible\t";
cout<<&var2<<endl;
cout<<var2<<endl;
return 0;
}
附上运行结果图。应该体会清楚哈!!!
接下来直接怼上重头戏–指针
一般教材书上出现指针时,直接声明指针一气呵成,让一些小伙伴都很懵逼
type *var-name = &var-name1;
type 指针类型
*解引用符【解引用仅适用于那些确实指向了某个对象的有效指针】
va-name指针变量名称
int *ip=&a;
这样让我们有时候很懵逼
我们可以这样理解
int *p;
p=&a;
这样就可以知道了var-name存储另一个变量的地址,*var-name就是表示指向另一个变量的值
下面这些代码会让你印象更深
#include<iostream>
using namespace std;
int main()
{
int a[10];
a[0]=1;
int b=2;
int *c;
int *d;
c=a;
d=&b;
cout<<"The address of a varaible ";
cout<<a<<endl;
cout<<"The address of *c varaible ";
cout<<c<<endl;
cout<<"the value of b varaible ";
cout<<b<<endl;
cout<<"the value of a varaible ";
cout<<*c<<endl;
cout<<"The address of b varaible ";
cout<<&b<<endl;
cout<<"The address of *d varaible ";
cout<<d<<endl;
return 0;
}
运行结果