On the problem of the transfer value of the SWAP function

Source: Internet
Author: User

#include <stdio.h>voidswap(int* p3,int* p4);intmain(){ int a = 9; intb = 8; int* p1 = &a; int* p2 = &b;  printf("%x %x\n",p1,p2); swap(p1,p2);  printf("%d %d\n",a,b); printf("%d %d\n",*p1,*p2);  printf("%x %x\n",p1,p2);   return0;}voidswap(int* p3,int* p4){ int* t; t = p3; p3 = p4; p4 = t;}

Beginner C's pointer type, will certainly write such a program, is the use of functions to exchange two values.

The above code is also very easy to think of, but the result of this code is wrong!!! The reason is that a function cannot have more than one return value!!

If more than one value is to be returned, use the method of upward communication (that is, the address of the argument as the variable).

In the process of single-step debugging, we can also see that the two times the address has not changed.

If you use single-step debugging, you can see that the values of P3 and P4 have indeed changed, meaning that the memory that P3 and P4 point to is indeed exchanged, but this exchange does not affect the memory that the P1 and P2,p1 and P2 point to are not changed.

It is equivalent to swapping the swap function only for the value of the address stored in the P3 and P4.

PS: In the direct operation of the address (pointer), you can think of the int * as a whole int, then the change in the P3,P4 is equivalent to the change of two int type variable, the variable of int in the called function will not be brought back to the main function without the return value. However, if you use a return value, but you cannot bring back two values, use the pointer type.

On the problem of the transfer value of the SWAP function

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.