It has been two or three years since training and learning C. At the beginning, I gave a brief introduction to pointers, but I didn't talk about memory management.
After several years of work, I feel that the foundation is becoming more and more important, and it is very helpful for the depth of understanding programming ideas.
Check <C Primer Plus> and write a small piece of code to verify that your understanding of the pointer is correct.
Environment: gcc version 4.4.5 (Debian 4.4.5-8)
C code
# Include <stdio. h>
Void s (int * I, int * j); // exchange address
Void s2 (int * I, int * j); // modify the value of the memory address pointing to the block.
Void p (int I, int j); // print the value
Void pp (int * I, int * j); // print the address
Int main (int argc, char const * argv [])
{
Int I = 0, j = 1;
P (I, j );
Pp (& I, & j );
S (& I, & j );
P (I, j); // The value remains the same, and the address of I j remains the same. Why? according to my understanding, only the memory area pointed to by the pointer can be changed. To change the address of the pointer variable, I want to assign values by equal signs only within the scope of the local variable of I j.
Pp (& I, & j );
S2 (& I, & j );
P (I, j );
Pp (& I, & j); // the IP address of I j remains unchanged.
Return 0;
}
Void s (int * I, int * j)
{
Int tmp;
Tmp = * I;
I = j;
J = & tmp;
Printf ("address change \ n ");
P (* I, * j );
Pp (I, j );
}
Void s2 (int * I, int * j)
{
Int tmp;
Tmp = * I;
* I = * j;
* J = tmp;
}
Void p (int I, int j)
{
Printf ("% d -- % d \ n", I, j );
}
Void pp (int * I, int * j)
{
Printf ("% p -- % p \ n", I, j );
}
Running result:
Reference
0 -- 1
0xbfe2fccc -- 0xbfe2fcc8
Address change
1 -- 0
0xbfe2fcc8 -- 0xbfe2fc9c
0 -- 1
0xbfe2fccc -- 0xbfe2fcc8
1 -- 0
0xbfe2fccc -- 0xbfe2fcc8
Author "ManGege's Blog"