当前位置:网站首页>Pointer and pointer of pointer

Pointer and pointer of pointer

2022-06-22 03:35:00 A rainy spring night

(Owed by: Happy rain in spring night http://blog.csdn.net/chunyexiyu)

1. introduction

Pointer and pointer of pointer , In essence , Both are storage addresses , In terms of language characteristics , One is a layer of pointers , One is a two-level pointer .

2. Pointer and pointer of pointer
void* p;
void** pp = &p;

The pointer And The pointer of the pointer ;

2. 1. Internal view

It's all pointers , Stored an address ;
The difference lies in a common variable address , A memory pointer variable address ;
But from a memory perspective , Is a variable address value ;

2. 2. From the compiler's point of view

The inspection of it is different ;
The two are different for compiler checking , The pointer can be redirected once , The pointer of the pointer can be redirected twice ;
A pointer can point to an address ;
The pointer of a pointer can point to the address of a pointer ;
Pointers and pointers to pointers cannot be used interchangeably , But cast is also possible .
for example :

  void* p = nullptr;
  void** pp = &p;
  void* pc = (void*)(pp);
  void** ppc = (void**) (p);
3. Why a pointer with a pointer ?

Personally, I think , Maybe it's mainly the need of identification and compiler checking ;
Or from the perspective of storage use , Both are storage addresses , adopt * Redirect the variable of the address location pointed to , The storage functions are consistent ;

Usage scenario of pointer :

  1. Scenarios that meet the needs of compiler recognition
  2. Scenarios that meet the needs of function value transfer
3.1 Meet the needs of compiler recognition

for example :
The following scene ,pp Want to store the address of a variable , To point to this variable , The variable itself is a pointer ;

void *p;
void** pp = &p;

for example :
The following scene ,pp Want to point to an array , This array is an array of pointers ;

void* parray[] = {nullptr, nullptr};
void** pp = parray;
3.2 Scenarios that meet the needs of function value transfer

for example :
We want the variable to be assigned in the function , Usually, you can pass the variable address in the past , But the variable itself is a pointer p;
A single-layer pointer passes a variable p Value ( That is to say p The direction of ), A double-layer pointer can pass through p The address of ;

void *p = nullptr;
getResource(&p);

void getResource(void** p){
    *p = new xxx(...);
}

— Personal understanding , For reference only

(Owed by: Happy rain in spring night http://blog.csdn.net/chunyexiyu)

原网站

版权声明
本文为[A rainy spring night]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220315370638.html