why and when is a double-pointer required?

后端 未结 3 1833
野性不改
野性不改 2021-01-16 04:40

I have been a sysadmin most of my life, but recently decided to practice some my dev knowledge and attempt a devops position. I have as such been practicing some C and Pytho

3条回答
  •  执笔经年
    2021-01-16 05:22

    In C, arguments to function are passed by values. Even pointers are passed by values.

    For example:

    #include
    #include
    int allocatingMemory(int* ptr)
    {
        ptr = malloc(sizeof(int)); 
        if(ptr==NULL)
            return -1;
        else 
            return 0;
    }// We are not returning the pointer to allocated memory
    
    int main(void)
    {
        int* ptr;
        int allocated = allocatingMemory(ptr);
        if(allocated == 0)
        {
            *ptr = 999;// Boom!!! 
            free(ptr);
        }
    
        return 0;
    }
    

    To overcome this issue, we use

    int allocatingMemory(int** ptr)
    {
        *ptr = malloc(sizeof(int));
        if(*ptr == NULL)
            return -1;
        else 
            return 0;
    }
    
    int main(void)
    {
        int* ptr;
        int isAllocated = allocatingMemory(&ptr);
        if(isAllocated == 0)
        {
            *ptr = 999;
            free(ptr);
        }
    
        return 0;
    }
    

    If you are working with linked lists and say for example, you want to modify the head. You will pass a pointer to pointer (Note that, it is not called as double pointer) to head node.

提交回复
热议问题