Pointer (pointer) summary

A description

A pointer "points" Another type of composite type.

And reference (reference) except that:

  1. Itself is a pointer to the object, to allow replication and copy pointer, and in its life cycle point may have several different objects;

  2. Pointer is not necessary to define the initial value is given, then it will have an uncertain value. But it is recommended to initialize all pointers, to avoid unnecessary mistakes.

Two, four states pointer

  1. Point to an object;
  2. It points to close at a position of the object space occupied;
  3. Null pointer, i.e., without any object point;
  4. An invalid pointer, i.e., a value other than the above case.

note:

Trying to copy or otherwise accessing an invalid pointer value will cause an error, but the compiler is not responsible for checking such errors!

The second and third forms of the pointer is valid, but also limited, attempts to access an object pointer such behavior is not allowed!

Third, access to the object address

Storing an address pointer to the object, the address needs to be obtained to take address character (&).

int ival = 5;
int *p = &ival; // p存放变量ival的地址、或者说p是指向变量ival的指针

In general, the type of the object pointer need it refers to an exact match!

Fourth, the use pointers to access objects

Pointer to an object, allow the dereference symbol (*) to access the object.

int ival = 5;
int *p = &ival;
cout << *p;

Fifth, null pointer

Null pointer does not point to any object, trying to use an empty can first check whether it is empty before pointer.

Several methods of generating null pointer:

int *p1 = nullptr; // C++11新标准, 最好使用新标准
int *p2 = 0;
int *p3 = NULL; // 需要cstdlib,等价于上一种方法

Int variables can not be directly assigned to a pointer, even if the value of the variable 0

Six, void * pointer

void * is a special type of pointer, can be used to store the address of the object easily.

Seven Pointers to Pointers

Is a pointer to an object, like other objects also has its own address, the address pointer thus allowing it again into another pointer to go.

int ival = 2;
int *pi = &ival;
int **ppi = &pi;

Dereference get the value of ival:

cout << *pi << endl;
cout << **ppi << endl;

Eight, a pointer reference

The reference itself is not an object, and therefore can not be defined is a pointer to; however pointer object, there may be a pointer to a reference.

int ival = 2;
int *p; // p是一个int型指针
int *&r = p; // r是一个对指针p的引用

r = &ival; // r引用了指针p,该语句为令p指针指向ival
*r = 0; // 解引用得到ival, 该语句为将ival的值改为0

Continuously updated in ......

Guess you like

Origin www.cnblogs.com/linzijie1998/p/11528924.html