C: Some misconceptions about pointer function

Source: Internet
Author: User

When we learn the pointers, we know that each number in memory occupies a certain byte, that is, the address, only take the address symbol &, so to exchange two number must be the corresponding memory of the two numbers swap, such as a=2;b=3; to make them interchangeable and output, let's try a function.

1#include"stdio.h"2 intTempintXinty)3 {4     intC;5C=x;6x=y;7y=C;8     }9 voidMain ()Ten { One     intb; AA=2; -b=3; - Temp (A, b); theprintf"A=%d,b=%d", A, b); -}

Obviously, this method does not, it is only on the surface interchange a A, a, and the function is only in memory when running, when the end, the function of memory is removed, let us look at a more misleading example:

1#include"stdio.h"2 intTempintXinty)3 {4 int*p,*q,t;5p=&x;6q=&y;7t=*p;8*p=*Q;9*q=T;Ten } One voidMain () A { -    intb; -A=2; theb=3; - Temp (A, b); -printf"a=%d,b=%d", A, b);  -}

The above function uses pointers, why or not? In fact, similar to the previous example, the main function in main () called the temp (A, A, b) passed as an argument to the int temp (int x,int y) parameter passed the value 2, 3; not a A, B address, and then take the address of 2,3, the result is 2,3 address interchange, however a =2,b=3 is still the same, next look at the right is an example:

1#include"stdio.h"2 intTempint*p,int*q)3 {4 intT;5t=*p;6*p=*Q;7*q=T;8 }9 voidMain ()Ten { One     intb; AA=2; -b=3; -Temp (&a,&b); theprintf"A=%d,b=%d", A, b);  -}

Run Result: The actual argument is temp (&a,&b); Swap the address of a, B.

C: Some misconceptions about pointer 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.