1. Example of pointer usage.
# Include <stdio. h>
# Include <ctype. h>
Void main ()
{
Int Var = 10;
Int * ptr_var;
Ptr_var = & var; // the pointer ptr_var points to the variable VAR.
// Output the VaR value and the address of the variable VAR.
Printf ("/nvar value: % d/N", VAR); // output 10.
Printf ("/nvar address: % x/N", & var); // output & VaR is the same as ptr_var.
// Output the ptr_var address.
Printf ("/nptr_var address: % x/N", & ptr_var );
// Output the pointer to the variable, the VaR value of the output variable, and the storage address of the var.
Printf ("/nvar value: % d/N", * ptr_var); // output 10.
Printf ("/nvar address: % x/N", ptr_var );
}
2. Indirectly assign a variable value to another variable through a pointer.
# Include <stdio. h>
# Include <ctype. h>
Void main ()
{
Int num1 = 50, num2 = 100;
Int * ptr1, * ptr2;
Ptr1 = & num1; // The ptr1 Pointer Points to the variable num1.
Printf ("/nnum1 variable value: % d/N", * ptr1 );
Printf ("/nnum1 address: % x/N", ptr1 );
Ptr2 = & num2;
Printf ("/nnum2 value: % d/N", * ptr2 );
Printf ("/nnum2 address: % x/N", ptr2 );
* Ptr2 = * ptr1; // point the variable value num1 pointed to by ptr1 to ptr2.
Printf ("The num2 value after the/n re-assignment is % d/N", * ptr2 );
Printf ("The num2 address after the/n re-assignment is % d/N", ptr2 );
}
3. Point the two pointers to the same variable.
# Include <stdio. h>
# Include <ctype. h>
Void main ()
{
Int number1 = 100;
Int * ptr1, * ptr2;
Ptr1 = & num1; // The ptr1 Pointer Points to the variable num1.
Printf ("/nnum1 address: % x/N", ptr1 );
Ptr2 = ptr1; // assign ptr1 to ptr2. the pointer ptr2 also points to the variable num1.
Printf ("/nptr2 address: % x/N", ptr2 );
}
4. Compare whether two pointers are equal.
# Include <stdio. h>
Void main ()
{
Int * ptr1, * ptr2;
Int value = 1;
Ptr1 = & value; // The ptr1 Pointer Points to the variable value.
Value + = 10;
Ptr2 = & value;
If (ptr1 = ptr2)
Printf ("/n two pointers point to the same address. /N ");
Else
Printf ("/n two pointers point to different addresses. /N ");
}
5. pointer to the array.
# Include <stdio. h>
Void main ()
{
Int data [] = {5, 10, 15, 20, 25 };
Int I = 0;
Int * PTR;
PTR = data; // PTR points to data [0], the first element of the array.
While (I <5)
{
Printf ("/n % d element address: % x, variable value: % d/N", I + 1, PTR, * PTR );
I ++;
PTR ++;
}
}
6. check whether a string of characters is a return character through a pointer.
# Include <stdio. h>
Void main ()
{
Char name [5] = {'M', 'A', 'D', 'A', 'M '};
Int flag = 1; // used for marking.
Char * Start, * end;
Start = Name;
End = Name + 4; // end = & name [4];
For (; Start <= end; Start ++, end --)
{
If (* start! = * End)
{
Flag = 0;
Break;
}
}
If (FLAG)
{
Printf ("/n this character is a return character. /N ");
}
Else
{
Printf ("/n this character is not a return character. /N ");
}
}