1 指针是什么
和所有变量一样,指针有自己的值和地址。指针的值是一个内存地址变量。
#include<iostream>
using namespace std;
int main()
{
int a = 3;
int * p = &a;
cout << "a: " << a << " a adress: " << &a << endl;
cout << "*p: " << *p << " p: " << p << " &p: " << &p << endl;
system("pause");
return 0;
}
为了看得更清晰一点,我将地址001EFD5C和001EFD50缩写为0x5C和0x50。一开始我们就说了指针既有值又有地址,在图中我们可以明显的看出来指针的地址是0x5C,指针的值是一个内存地址变量。p指向的是a的地址0x5C,也就是p的值。p的值有了,那p的地址呢,就是0x50。
Tips:解引用,有时候会看到这个词,意思就是给出指针指向地址上存储的值,也就是我们例子中的*p = a = 3。
2 指针的基本操作
大致有赋值,解引用,取地址,指针和整数相加(减),指针递增(递减),指针求差,指针的比较。用一个例子说明
#include<iostream>
using namespace std;
int main()
{
int a[] = { 1,2,3,4,5 };
int * p = a; //把地址赋值给指针 等价于int * p = &a[0],指向数组a的首地址
int * p1 = &a[2];
//解引用,取地址
cout << "*****解引用,取地址*****\n";
cout << "*p: " << *p << " p: " << p << " &p: " << &p << endl;
cout << "*p1: " << *p1 << " p1: " << p1 << " &p1: " << &p1 << endl;
//指针和整数相加(减)
int *p2 = p + 4; //p2指向a[4]
int *p3 = p1 - 1;//p3指向a[1]
cout << endl;
cout << "*****指针和整数相加(减)*****\n";
cout << "*p2: " << *p2 << " p2: " << p2 << " &p2: " << &p2 << endl;
cout << "*p3: " << *p3 << " p3: " << p3 << " &p3: " << &p3 << endl;
//指针递增(递减)
p++; //p指向a[1]
p1--;//p1指向a1[1]
cout << endl;
cout << "*****指针递增(递减)*****\n";
cout << "*p: " << *p << " p: " << p << " &p: " << &p << endl;
cout << "*p1: " << *p1 << " p1: " << p1 << " &p1: " << &p1 << endl;
//指针求差
cout << endl;
cout << "*****指针求差*****\n";
cout << "p2 = " << p2 << " p3 = " << p3 << " p2 - p3 = " << p2 - p3 << endl;
//指针的比较(两个指针都是指向相同类型的对象)
cout << endl;
cout << "*****指针的比较*****\n";
if (p2 == p3)
cout << "p2 equals to p3" << endl;
else
cout << "p2 is not equal to p3 " << endl;
if (p == p1)
cout << "p equals to p1" << endl;
else
cout << "p is not equal to p1 " << endl;
system("pause");
return 0;
}
注意:千万不要解引用未初始化的指针,像是这样
int * p; //未初始化的指针,指向的地址未知
*p = 3;//error,想把3存放在p指向的地址,可是p指向哪里我们不知道
3 指针和数组
#include<iostream>
using namespace std;
void show(const int arr[],int n)
{
cout << "arrray : ";
for (int i = 0; i < n; i++)
{
cout << " " << arr[i];
}
}
int sum_arr(const int *arr, int n)//为了保护数组中数据不被更改,使用了指向const的指针,表明该函数不会使用指针改变数据
{
int sum = 0;
for (int i = 0;i < n; i ++)
{
sum += *(arr++);
}
return sum;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int *p; //若p = a; 那么a[i] = *(p + i)
show(a, sizeof(a) / sizeof(int));
cout << "\nsum = " << sum_arr(a, sizeof(a) / sizeof(int)) << endl;
system("pause");
return 0;
}
4 指针和结构体(指向结构的指针)
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
struct Person {
string name;
double cash;
double card;
};
double sum_p(const struct Person *pp)//传递结构的地址,参数是指针
{
return (pp->card + pp->cash);
}
double sum(struct Person p) //传递结构
{
return (p.card + p.cash);
}
int main()
{
struct Person z_san = { "z_san",4323.45,120.32 };
cout << "\nsum() = " << sum(z_san) << endl;
cout << "\nsum_p() = " << sum_p(&z_san) << endl;
system("pause");
return 0;
}