In C ++, the pointer, pointer reference, and pointer difference are shown in the example and result:
# Include "stdafx. H"
# Include <iostream>
Using namespace STD;
Void freeptr1 (int * ptr1)
{
Delete ptr1;
Ptr1 = NULL;
}
Void freeptr2 (int * & ptr2)
{
Delete ptr2;
Ptr2 = NULL;
}
Void freeptr3 (INT ** ptr3)
{
Delete * ptr3;
* Ptr3 = NULL;
}
Void main ()
{
Cout <"---------------------------------------" <Endl;
Int * P1 = new int;
* P1 = 1;
Cout <"* P1 =" <* P1 <Endl;
Freeptr1 (P1 );
Cout <"after call freeptr1" <Endl;
If (P1! = NULL)
{
Cout <"P1 is not null" <Endl;
Cout <"* P1 =" <(* P1) <Endl;
}
Cout <"---------------------------------------" <Endl;
Int * P2 = new int;
* P2 = 2;
Cout <"* P2 =" <* P2 <Endl;
Freeptr2 (P2 );
Cout <"after call freeptr2" <Endl;
If (P2! = NULL)
{
Cout <"* P2 =" <* P2 <Endl;
}
Else
{
Cout <"the P2 is null" <Endl;
}
Cout <"---------------------------------------" <Endl;
Int * P3;
P3 = new int (3 );
Cout <"* P3 =" <* P3 <Endl;
Freeptr3 (& P3 );
Cout <"after call freeptr3" <Endl;
If (P3! = NULL)
{
Cout <"* P3 =" <* P3 <Endl;
}
Else
{
Cout <"the P3 is null" <Endl;
}
Cout <"---------------------------------------" <Endl;
System ("pause ");
}
Result:
Comments:
Pointer to P1:
Cout <"---------------------------------------" <Endl;
Int * P1 = new int;
* P1 = 1;
Cout <"* P1 =" <* P1 <Endl;
// Freeptr1 (P1 );
Void freeptr1 (int * ptr1)
{
Delete ptr1;
Ptr1 = NULL;
}
Cout <"after call freeptr1" <Endl;
If (P1! = NULL)
{
Cout <"P1 is not null" <Endl;
Cout <"* P1 =" <(* P1) <Endl;
}
Cout <"---------------------------------------" <Endl;
P2:
Before calling:
After the call:
Note: If you copy the value of a function parameter, you can copy the pointer (the address saved in the pointer) even if the pointer is passed, it's not a copy of the value indicated by the address in the pointer! Original article address