Review pointers in C Language

Source: Internet
Author: User

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"
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.