C/C #/java strange parameter passing and interpretation

Source: Internet
Author: User

Let's take a look at the C language code below.

#include <stdio.h>void s(char *b){    printf("%s\n",b);    b="aaaa";    printf("%s\n",b);}int main(){    char *a="hello";    s(a);    printf("%s\n",a);}

The output of my first impression should be changed

Hello

Aaaa

Aaaa

But this is wrong.

 

The actual output is

 

Hello

Aaaa

Hello

Isn't it weird? Actually Think About It. C language parameters are actually passed values (pointers are also passed pointer values). When s (a) is called, the stack opens up a parameter zone to pass the pointer value of. When the statement B = "aaaa"; is executed, the B pointer value in the parameter area is changed to the address of "aaaa", but the value of a is not changed, therefore, when the main function runs printf ("% s \ n", a);, the original value is printed. Let's look at the java code.
public void extractXPS(StringWriter sw) {    sw=new StringWriter();    sw.write("Hello World");}void m(){    StringWriter sw=new StringWriter();  System.out.println(sw.toString());        }

What kind of output will be produced by the execution method m?

Only "" is output, that is, "Hello World" is not output ".

In java and C #, the object parameter actually passes a reference (= pointer), which can be modified. However, if you point to another object again, after jumping out of this method, it does not affect the original objects in the original caller.

 

 

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.