Several Right and Wrong Ways of Pointer in C Language
Error 1,
void Swap(int a, int b)//未传指针
{
int tmp = a;
a = b;
b = tmp;
}
In this way, in the code that calls the function to exchange, it can be seen that it is only a simple exchange of the respective stored addresses. No pointer is passed!
Error 2,
void Swap(int* p1, int* p2)//未解引用
{
int* tmp = p1;
p1 = p2;
p2 = tmp;
}
Although the addresses of a and b are passed in in this way, the corresponding addresses are not operated. No dereference!
Error 3.
void Swap(int* p1, int* p2)//有野指针 tmp的值未初始化
{
int* tmp;
*tmp = *p1;
*p1 = *p2;
*p2 = *tmp;
}
This method uses pointer transfer and dereference, but the value of tmp is not initialized!
The right way
void Swap(int* p1, int* p2)
{
int tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
to sum up
1. If a function wants to modify the value of another function, it must pass pointers and dereference.
2. Wild pointers and dangling pointers: addresses without access rights.
3. Null pointers (NULL): the current pointer is invalid