C-language pointer-based pointer exchange between two numbers (Code instances) and pointer instances

Source: Internet
Author: User

C-language pointer-based pointer exchange between two numbers (Code instances) and pointer instances

Exchange two numbers with pointers:

Void swap (int * p, int * q) {int temp; temp = * p; * p = * q; * q = temp;} int main () {int a = 3, * p, c = 5, * q; p = & a; // assign the address of variable a to pointer p, that is, p points to aq = & c; swap (p, q); printf ("a = % d, c = % d \ n", a, c); return 0 ;}

Note: In a sub-method, two numbers can only be passed by reference. Because java is passed by value, and c can pass a pointer, c can modify the value of a temporary variable.

Java cannot modify the value of a temporary variable. java obtains the running result of the method through the return value:

Public static void main (String [] args) {int a = 3, B = 5; fun (a, B); System. out. println ("a =" + a + "; B =" + B);} private static void fun (int p, int q) {p * = 2; q * = 2 ;}

C can directly modify the value of the Temporary Variable through the pointer:

Void fun (int * p, int * q) {* p * = 2; * q * = 2;} int main () {int a = 3, * p, c = 5, * q; p = & a; // assign the address of variable a to the pointer p, that is, p points to aq = & c; fun (p, q ); printf ("a = % d, c = % d \ n", a, c); return 0 ;}

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.