(c + +) A first-level pointer and a two-level pointer in a function parameter pass

Source: Internet
Author: User

(c + +) A first-level pointer and a two-level pointer in a function parameter pass

Main Content:

1, level hands and level two pointers

2. Example of function pointer passing

3. When do I need to pass level two pointers?

4, level two pointer in the list of use

1, level hands and level two pointers

First level pointer: that is, we generally say that the pointer is the memory address;

Secondary pointers: pointers to pointers, addresses;

Such as:

int a=1;

int *p=&a; P is the address of the a variable, and the value of a can be obtained by *p

int **q=&p; Q is the address of the p-pointer, and the value of a can be obtained by **q

2. Example of function pointer passing

Program 1:

12345678910111213141516 #include<stdio.h>void fun(int*p){    intb=100;    p=&b;}intmain(){    inta=10;    int*q;    q=&a;    printf("%d\n",*q);    fun(q);    printf("%d\n",*q);    return0;}

Operation Result:

10

10

Program 2:

12345678910111213141516 #include<stdio.h>voidfun(int**p){    intb=100;    *p=&b;}intmain(){    inta=10;    int*q;    q=&a;    printf("%d\n",*q);    fun(&q);    printf("%d\n",*q);    return0;}

Operation Result:

10

100

Program 3:

12345678910111213141516171819 #include<stdio.h>#include<stdlib.h>voidmyMalloc(char*s){     s=(char*)malloc(100);}intmain(){     char*p=NULL;     myMalloc(p);     if(p==NULL)        printf("P is not changed!\n");     else{        printf("P has been changed!\n");        free(p);     }     return0;}

Operation Result:

P is not changed!

Program 4:

12345678910111213141516171819 #include<stdio.h>#include<stdlib.h>voidmyMalloc(char**s){     *s=(char*)malloc(100);}int main(){     char*p=NULL;     myMalloc(&p);     if(p==NULL)        printf("P is not changed!\n");     else{        printf("P has been changed!\n");        free(p);     }     return 0;}

Operation Result:

P has been changed!

3. When do I need to pass level two pointers?

From the above example, we can see that in some cases, when a function parameter passes a first-level pointer, it changes the pointer in the body of the function, and does not change the original pointer, but passes a level two pointer, which is why?

When passing a first-level pointer, only the memory variable pointed to by the pointer is valid;

When passing a level two pointer, it is only valid to change the Pointer's direction;

Here's a simple analysis:

When a function passes a parameter, the compiler always makes a copy of each function parameter, that is, a copy;

For example:

void fun (int *p), pointer parameter p is a copy of _p, the compiler causes _p=p,_p and p to point to the same memory space, if the function is modified within the _p point of the content, it will cause the content of P also make corresponding changes;

But if _p in the function requests a new memory space or points to another memory space, _p points to the new memory space, and p still points to the original memory space, so the function returns p or the original P.

In this case, not only does not realize the function, but each time to apply for new memory space, but not to release, because the memory space is not passed out, it is easy to cause memory leaks.

void Fun (int **p), If the function argument is the address of the pointer, you can pass the parameter p to the new assignment or to the new point of memory address, so that a valid pointer operation is Implemented.

If you feel that level two pointers are difficult to understand, you can also pass dynamic memory in the form of function return values ( Remember that you cannot return stack memory), such as:

1234567891011121314151617181920 #include<stdio.h>#include<stdlib.h>char* myMalloc(){     char*s=(char*)malloc(100);     returns;} intmain(){     char*p=NULL;     p=myMalloc();     if(p==NULL)        printf("P is not changed!\n");     else{        printf("P has been changed\n");        free(p);     }     return 0;}

Knowing the above, it is not difficult to understand the above four small program execution Results.

4, level two pointer in the list of use

In the operation of a linked list or tree, A level two pointer is also required,

For example, Create a list of head pointers:

In initializing the list function, passing in the head pointer and allocating space for the pointer in the function, you should use a level two pointer, such as void Initlinklist (Node **head);

In the process of adding a delete node, we did not change the pointer of the function parameter, but instead, by passing in a pointer such as node *head, we found the position where we want to delete the node, and did not change the pointer, so after exiting the function, the pointer has no Effect.

(1) hover pointer in C + +: a pointer that declares but does not have a value, pointing to any space in Memory. One way to avoid suspending the pointer is to start with a value of NULL

(2) "wild pointer" is not a null pointer, it is a pointer to "junk" memory. It is generally not wrong to use a null pointer because it is easy to judge with an if Statement. But a "wild pointer" is dangerous, and the IF statement does not work on it. There are two main causes of wild pointers:

one, the pointer variable is not initialized. Any pointer variable that has just been created does not automatically become a null pointer, and its default value is random, and it can be arbitrary. therefore, The pointer variable should be initialized at the same time it is created, either by setting the pointer to null or by pointing it to legitimate memory.
second, After the pointer p is free or delete, it is not set to null, which makes the person mistakenly think P is a valid pointer. Although the names of free and delete are ferocious (especially delete), They simply release the memory that the pointer refers to, but do not kill the pointer itself. usually, the statement if (p! = NULL) is used for Error-proof handling. unfortunately, The IF statement is not error-proof at this point because even if p is not a null pointer , it does not point to a valid block of Memory. Cases:
Char *p = (char *) malloc (100);
strcpy (p, "hello");
Free (p); The memory referred to by P is freed, but the address referred to by P remains unchanged
If (p! = NULL)//does not play an anti-error role
strcpy (p, "world"); Error

third, Another issue to note: do not return a pointer or reference to the stack memory, because the stack memory will be released at the end of the Function. strlen is to char*, string not, This is very easy to make people misunderstand ah

Iv. mistakes that we make easy:

For the second error is easy to appear in C + +, such as in the definition of the class constructor and destructor, if in the constructor of the dynamic open (new), in the destructor to release, however, we generally delete the memory after the end of it, as everyone knows, Pointer to the previous memory is a wild pointer (stray pointer), alittle careless, will be wrong, when you assign value to the unknown area, good luck will be the program run error, if bad luck, it is likely to cause the system crash!
Workaround: make a pointer to an unknown region (a pointer that is just defined or free of Memory) equal to null or point to a constant, and then use the pointer to determine NULL

whether or not you want to set to null after the delete occurs? The only criterion is the future will not use it, if it is possible to use, it must be set to null, otherwise, unless the performance requirements of the software is very strong, otherwise, although every time after the delete is set null good to do so, will never run error, the potential consequences is that, This null-value operation wastes less than one out of 10,000 seconds of your Time.

V. Knowledge Supplement:

In general, the memory leaks that we often say refer to the leaks in heap memory . Heap memory means that the program is allocated from the heap, arbitrarily sized (the size of the memory block can be determined during the Program's run time), and the freed memory must be displayed after Use. Applications typically use functions such as malloc,realloc,new to allocate a piece of memory from the heap, and after use, the program must be responsible for calling free or delete to release the memory block, otherwise the memory will not be reused, we say this memory leaks

(c + +) A first-level pointer and a two-level pointer in a function parameter pass

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.