Analysis on the function of pointer

Source: Internet
Author: User

This article mainly introduces a usage of pointers to pointers. Therefore, we will not talk about pointers or pointer pointing to them here. Their basic code is directly used (Purpose: Use a function to dynamically apply for memory, and assign values. Output the value after calling the function.) [cpp] # include <stdio. h> # include <stdlib. h> typedef struct Data {int da;} Data; void fun (Data * p); int main () {Data * d; fun (d ); printf ("% d", d-> da); return 0;} void fun (Data * p) {p = (Data *) malloc (sizeof (Data )); p-> da = 2;} I suggest you run it directly to check the results, and you will find an error. Here I suggest you think about it first and then look at the following code: [cpp] # include <stdio. h> # include <stdlib. h> typedef struct Data {int da;} Data; void fun (Data ** p); // here Int main () {Data * d; fun (& d); // printf ("% d", d-> da); return 0 ;} void fun (Data ** p) // here {(* p) = (Data *) malloc (sizeof (Data); // here (* p) -> da = 2; // changed here} It is not difficult to find out that the changed Code uses a pointer pointing to the pointer. Why can't I use the pointer directly? Www.2cto.com because the void fun (Data * p) parameter in the first code is passed by value. The call function automatically defines a temporary variable to store the copy of the real parameter. The memory dynamically allocated in fun is not pointed to by the pointer variable d in the main function, the pointer variable d in main is undefined from start to end. How can this problem be solved? Use a pointer to the pointer to pass in the address of the pointer variable d in main. In this way, the memory space address allocated in fun is stored in the pointer variable d. Here, one of the functions of the pointer is self-evident.

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.