C language beginners-questions about pointer as a parameter and changing its value

Source: Internet
Author: User

Example 1:
[Cpp]
# Include <stdio. h>
Int f (int * p ){
P = p + 1;
Return printf ("% d \ n", * p );
}
Void main (){
Int a [] = {1, 2 };
Int * p = a; // the pointer p is the first address.
F (p); // call
Printf ("% d", * p); // The value of p will not change.
}

 
Result:
2
1
Press any key to continue
 
Example 2:
[Cpp]
# Include <stdio. h>
Void z (int * p ){
P = p + 1;
* P = 100;
}
Void mian (){
Int a [] = {1, 2 };
Int * p =;
Z (p); // call
Printf ("a [1] = % d", * (p + 1); // the value in the memory space pointed to by the pointer (p + 1) has changed
}

 
Result:
A [1] = 100
Press any key to continue

Through the above two examples, we can conclude that when a pointer is passed as a parameter, its value cannot be changed in other functions (the address pointed by this pointer), but it can be changed.
The value in the address.
So to realize the value exchange between the two first-level pointers, we need to use the second-level pointer: (pointer q points to a, pointer p points to B, implement q points to B, p points to)
[Cpp]
# Include <stdio. h>
Void exchange (int ** x, int ** y ){
Int * temp;
Temp = * x; // * x = * qq = &
* X = * y;
* Y = temp;
}
 
Void main (){
Int a = 100;
Int B = 12;
// Define the pointer
Int * q = &;
Int * p = & B;
Int ** qq = & q;
Int ** pp = & p;
// Output
Printf ("q = % p \ n", q );
Printf ("p = % p \ n", p );
// Call the function for conversion
Exchange (qq, pp );
 
Printf ("========= changed ===============\ n ");
Printf ("q = % p \ n", q );
Printf ("p = % p \ n", p );
}

Result:
Q = 0012FF44
P = 0012FF40
========= After the change ==========
Q = 0012FF40
P = 0012FF44
Press any key to continue


From like7xiaoben

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.