C Language Learning Guide (4)
Pointer: it can effectively represent complex data structures, dynamically allocate dynamic space, facilitate the use of strings, effectively use arrays, and directly process memory units.
If you don't know the pointer, you don't know the essence of C language.
Address: The system allocates a memory unit for each variable. Each byte in the memory area has a number, which is the address"
Pointer definition; base type * pointer variable name
For example, int * pointer;
You can use a value assignment statement to get the address of another variable and point it to one variable.
Example 1 using pointer variables to access Integer Variables
/******************** Function: access the integer variable ************************/# include <stdio. h> void main () {int A, B; int * pointer1, * pointer2; A = 100; B = 10; pointer1 = & A; pointer2 = & B; printf ("% d \ n", a, B); printf ("% d \ n", * pointer1, * pointer2 );}
For example 2, for integers A and B, the values are output in the ascending order.
/******************* Function: Use the pointer function to compare the two numbers, output ********************/# include <stdio. h> void main () {void swap (int * P1, int * P2); int A, B; int * pointer1, * pointer2; scanf ("% d ", & A, & B); pointer1 = & A; pointer2 = & B; if (a <B) Swap (pointer1, pointer2 ); printf ("% d \ n", a, B);} void swap (int * P1, int * P2) {int temp; temp = * P1; * P1 = * P2; * P2 = temp ;}
Example 3 in ancient times, the Hanoi Tower had a fan tower with three seats A, B, and C. at first, there were 64 plates on a, which were not of the same size. The size of the plates was lower and smaller than the upper. An old monk wanted to move 64 plates from A to C, during the process of moving, always keep the dashboard down and the small disk above.
/********************* Function: solve the Problem of Hanoi Tower with recursion *********************/# include <stdio. h> void main () {void Hanoi (int n, char one, char two, char three); int m; printf ("input the number of the diskes: \ n "); scanf (" % d ", & M); printf (" the step of moving % d diskes: \ n ", m); Hanoi (m, 'A', 'B', 'C');} void Hanoi (INT N, char one, char two, char Three) {// move n disks from the first to the second and then to the third void move (char X, char y); If (n = 1) Move (one, three ); else {Hanoi (n-1, one, three, two); move (one, three); Hanoi (n-1, two, one, three) ;}} void move (char X, char y) {printf ("% C --> % C \ n", x, y );}