Memory usage across functions

Source: Internet
Author: User

1.To modify the value of a real parameter through a function without a return value, the address must be passed.

Void f (int * p)

{

* P = 100;

}


Int main ()

{

Int a = 9;

F (& a); // No matter what type of variable, the address must be passed here to modify its value through the function. P = & a, then * p is equivalent to

Printf ("a = % d \ n", );

Return0;

}

2.Memory usage across functions

Question: In the next program, we can call the function fun to point the pointer Variable p in the main function to a valid integer unit.

A main ()

{

Int * p;

Fun (p); // the address of p is not passed here, so it must be wrong.

...

}

Int fun (int * q)

{

Int s;

Q = & s;

}


B main ()

{

Int * p;

Fun (& p );

...

}

Int fun (int ** q)

{

Int s;

* Q = & s;

}

// It seems correct, but it is actually incorrect. If the p address is passed to q, * q is equivalent to p, p points to s, but the variable s is valid only within the fun function. After the fun function is executed, s memory is released, not a legal integer unit


C main ()

{

Int * p;

Fun (& p );

...

}

Int fun (int ** q)

{

* Q = (int *) malloc (sizeof (int); // correct. The memory allocated by malloc must be automatically released by free.

}


D main ()

{

Int * p;

Fun (p); // No address is added for direct error judgment

...

}

Int fun (int * q)

{

Q = (int *) malloc (sizeof (int ));

}


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.