C + + Primer function Pass value 1

Source: Internet
Author: User

Don't look at C + + primer never know how bad their base is


There are generally two ways to pass values of functions: value passing, reference passing.


The value is passed in the following two ways:

void func (int a) {//}void func1 (int *a) {//}

Both Func and FUNC1 are implemented by copying memory.

Func1

int m = ten; func1 (int *a);//The process is: a = &m;  Then the M is indirectly manipulated by the pointer *a

Pass Reference

void Func2 (int &a) {//}
A reference is an alias of a variable, and no memory copy occurs.



A typical interview question:

void GetMemory1 (char *p) {    p = (char *) malloc (100);} void Test1 (void) {    char *str = NULL;    GetMemory1 (str);     strcpy (str, "Hello World");    printf (str);} <p></p><pre name= "code" class= "cpp" >//p = str;//p = malloc (...); Is there a half wool relationship between/p and str?

Char *getmemory2 (void) {char p[] = "Hello World"; return p;} void Test2 (void) {char *str = NULL; str = GetMemory2 (); printf (str);} Char *getmemory3 (void) {return "Hello World";} void Test3 (void) {char *str = NULL; str = GetMemory3 (); printf (str);} Hello world is printed in TEST3 because it returns a constant area and has not been altered. Hello world is not necessarily printed in Test2 because it points to a stack. void GetMemory4 (char **p, int num) {*p = (char *) malloc (num);} void Test4 (void) {char *str = NULL; GetMemory3 (&STR, 100); strcpy (str, "Hello"); printf (str);  }//memory does not release void Test5 (void) {char *str = (char *) malloc (*), strcpy (str, "Hello"), free (str), if (str! = NULL) {strcpy (str, "World"); printf (str); }}//STR is a wild pointer, the printed result is unknown void Test6 () {char *str= (char *) malloc (), strcpy (str, "Hello"); str+=6; free (str); if (str!=null {strcpy (str, "World"); printf (str);}} VC assertion failed, execution error











C + + Primer function Pass value 1

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.