指针
指针本身就是一个对象,允许对指针赋值和拷贝,而且在指针的生命周期内它可以指向几个不同的对象;
指针无须在定义时赋初值。和其他内置类型一样,在块作用域内定义的指针如果没有初始化,也将拥有一个不确定的值。
#include <iostream>
using namespace std;
int main()
{
int x = 25, y = 50, z = 75; // Three int variables
int *ptr; // Pointer variable
// Display the contents of x, yr and z
cout << "Here are the values of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
// Use the pointer to manipulate x, y, and z
ptr = &x; // Store the address of x in ptr
*ptr *= 2; // Multiply value in x by 2
ptr = &y; // Store the address of y in ptr
*ptr *=2; // Multiply value in y by 2
ptr = &z; // Store the address of z in ptr
*ptr *= 2; // Multiply value in z by 2
//Display the contents of x, y, and z
cout << "Once again, here are the values " << "of x, y, and z:\n";
cout << x << " " << y << " " << z << endl;
return 0;
}
Here are the values of x, y, and z:
25 50 75
Once again, here are the values of x, y, and z:
50 100 150
double dval;
double *pd = &dval;//double* pd = &dval
double *pd2 = pd;
指针的值应属于下列4中状态之一:
- 指向一个对象;
- 指向紧邻对象所占空间的下一个位置;
- 空指针,意味着指针没有指向任何对象;
- 无效指针,也就是上述情况之外的其他值。
空指针
int *p1 = nullptr;//best
int *p2 = 0;//在大多数计算机中,用户程序不能访问地址为 0 的内存,因为它被操作系统数据占用。这使得 0 成为指示无效内存位置值的安全选择。
int *p3 = NULL;//need #include cstadlib
int zero = 0;
p2 = zero;//错误,不能把int变量直接赋给指针
void* 指针
指向指针的指针
int* p1,p2;//p1为指针,p2是int
int ival =1024;
int *p1 = &ival;//p1指向一个int型的数
int **p2 = &p1;//p2指向一个int型指针
cout<<*p2;//cout<<&p1
cout<<**p2;//cout<<1024
指向指针的引用
int i = 42;
int *p;
int *&r = p;//r是指向P的引用
r = &i;//r赋值&i,就是令p指向i
*r = 0;//i = 0