Memory operations in Functions

Source: Internet
Author: User

1. Address Transfer Request memory problems.

Let's look at the following example.

Struct complex_t // plural {int real; // real int imag; // virtual number}; int create (complex_t * P, unsigned int N) {P = new complex_t [N]; // apply for N complexif (P = NULL) Return-1; else return 0 ;}

Then, call this function in the main function:

Complex_t * comps = NULL; If (create (comps, 10) <0) // call the function {printf ("create failed \ n"); Return-1 ;} if (comps = NULL) {cout <"comps is null \ n"; Return-1;} // other operations

The first parameter of the create function, type: complex_t *. Then, a bucket is allocated to P in create. The pointer is used as a parameter to return the applied memory address.
In fact, comps = NULL after execution.
When the create function is called in the main function, comps is assigned to P. That is, the pointer P points to the same storage space as comps. However, in create, P = new complex_t [N] Makes P point to a new bucket. At this time, comps still points to the original storage space. Therefore, the changes made to P in create have no impact on comps.
The parameter complex_t * in the create function can be compared to int as a whole.

Through the above analysis, it is not difficult to provide a solution:

Int create (complex_t ** P, unsigned int N) {* P = new complex_t [N]; // apply for N complexif (P = NULL) Return-1; else return 0 ;}

 

 

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.