Allocate memory space for function parameters

Source: Internet
Author: User
1 void fun (char * c) 2 {3 4 c = new int [10]; 5 6}

This function is used to allocate space for parameter c, but in fact it is counterproductive. parameters passed to fun are not allocated externally.

To achieve this goal, you need to use the pointer or pointer reference.

1 void fun (char ** c) 2 {3 4 * c = new int [10]; 5 6}
1 void fun (char * & c) 2 {3 4 c = new int [10]; 5 6}

 

 

 

Cause:

Both the passed variables and pointers are passed by value, and the transferred to the function is another copy, except that the variable itself is passed when the variable is passed, the pointer is a copy of the passed pointer itself. Therefore, you can change the pointer to the memory, but not the pointer itself.

However, if it is passed by reference, you can change the pointer itself.

For example:

1 void fun (char * c) 2 {3 c = NULL; 4 printf ("% p \ n", c); 5} 6 7 8 int main () 9 {10 char * c = (char *) malloc (2); 11 fun (c); 12 printf ("% p \ n", c); 13 14 return 0; 15}

The result should be

1 [ubuntu @ root test] #./test2 (nil) 3 0x80f8008

 

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.