How does the C ++ pointer Parameter Pass the memory ?, Pointer Transmission

Source: Internet
Author: User

How does the C ++ pointer Parameter Pass the memory ?, Pointer Transmission

Several examples are provided to illustrate the memory transfer problem of the C ++ pointer parameter.

Example 1:

Void GetMemory (char * p, int num)

{

P = (char *) malloc (sizeof (char) * num );

Return;

}

Int main (void)

{

Char * str = NULL;

GetMemory (str, 30 );

Std: cout <str <std: endl; // str is still NULL

}

Analysis: If the function parameter is a pointer, do not expect this pointer to apply for dynamic memory. In example 1, the main function calls GetMemoty (str, 30) and does not enable str to obtain the expected memory. str is still NULL. In the GetMemory function, the compiler always creates a temporary copy for each parameter of the function. The copy of the pointer parameter p is _ p, and the compiler makes _ p = p. If the program in the function modifies the content of _ p, the content of parameter p is modified accordingly. This is why pointers can be used as output parameters. In example 1, _ p applied for a new memory, but changed the address of the memory indicated by _ p, but p was not changed at all. Therefore, the GetMemory function cannot output anything. In fact, each execution of GetMemory will leak a piece of memory because the memory is not free to be released. If you need to use the pointer parameter to request memory, you should use "pointer to Pointer" instead. For details, see Example 2.

Example 2:

Void GetMemory_2 (char ** p, int num)

{

* P = (char *) malloc (sizeof (char) * num );

Return;

}

Int main (void)

{

Char * str = NULL;

GetMemory (& str, 30 );

Strcpy (str, "hello world ");

Std: cout <str <std: endl;

Free (str );

}

Analysis: the temporary copy of * p in the GetMemory_2 function parameter is _ * p. In the function, a new memory is applied, which is equivalent to changing the content of pointer _ * p, thus, the content of * p is changed, so the memory application is successful.

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.