The best way to understand a thing is to know its purpose.
My understanding of pointers is simply one sentence: If you change the value of a variable (including basic variables, struct, classes, pointers) when calling a function ), then you need its pointer.
Since C/C ++ always copies a parameter when calling a function, you cannot change the original content (Java references objects ). Therefore, you need a pointer to directly change the memory content of that variable. Code:
#include "stdio.h"void changeValue(int a, int b);void changeValuePtr(int* pa,int b);void changePtrValue(int* pa , int* pb);void changePtrValuePtr(int* *a ,int* pb);int main(void){ int a = 0 ; int b = 3 ; changeValue(a,b); printf("calling changeValue a = %d\n",a); changeValuePtr(&a,b); printf("calling changeValuePtr a = %d \n",a); a = 0 ; changePtrValue(&a,&b); printf("calling changePtrValue a = %d \n",a); int* ptra = &a; changePtrValuePtr(&ptra , &b); printf("calling changePtrValuePtr a = %d \n",a); printf("calling changePtrValuePtr *ptra %d \n",*ptra);}void changeValue(int a , int b){ a = b ; return ;}void changeValuePtr(int* pa,int b){ *pa = b ; return ;}void changePtrValue(int* pa , int* pb){ pa = pb ; return ;}void changePtrValuePtr(int** pa ,int* pb){ *pa = pb ; return ;}
Result:
To change the value of A, you must input a pointer to. If you want to direct the pointer of A to B. Then you must pass in the pointer of. If you change the value of a variable (including basic variables, struct, classes, and pointers) when calling a function, you need its pointer.
Let's take a look at the Linux function int pthread_join (pthread_t th, void ** thread_return). This function is waiting for a thread to return, and the first parameter is the thread ID, put the content returned by the thread in thread_return. If you have learned Java, void * can be understood as an object, which can be forcibly converted to any variable (struct, class, basic variable ). We can use malloc to open up a piece of memory in a thread. In the pthread_join function, you need to point the thread_return pointer to the memory you opened. Therefore, to change the value of a pointer variable, we need the pointer of this pointer. Therefore, when we call the pthread_join function, we need to input a void **.
Understanding pointers and pointers