为什么以及何时需要双指针? [英] why and when is a double-pointer required?

查看:34
本文介绍了为什么以及何时需要双指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一生中的大部分时间都是系统管理员,但最近决定练习我的一些开发知识并尝试担任 DevOps 职位.因此,我一直在练习一些 C 和 Python 技能,并编写了一些将数字插入链表的代码.

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 Python skills and wrote some code for inserting a number into a linked list.

void list_insert(struct list *h, int d)
{
        struct list *elem = malloc(sizeof(struct list));

        elem->data = d;
        elem->next = NULL;

        if (!h) {
                h = elem;
        } else {
                elem->next = h;
                h = elem;
        }
}           

我注意到这个函数似乎没有改变变量 h 的外部视图(即传递给 list_insert 的任何内容),我注意到在插入函数末尾打印似乎有效.因此,尝试在网上寻找答案后,我找不到任何东西,很明显,但我发现大多数列表实现都会有双指针.我将函数更改为使用双指针,然后它突然开始工作.有人能帮我理解这里发生了什么,因为我知道指针管理是一个重要的概念,我想我理解指针是什么以及它与内存的关系,但我不认为我明白为什么单个指针没有改变,而双指针可以.

I noticed that this function doesn't seem to alter the outside view of the variable h (i.e whatever is passed to list_insert) and I noticed that printing at the end of the insert function seems to work. So having tried to look for answers online, I couldn't find anything, obvious but I found most list implementations would have double-pointers. I changed my function to use double-pointers and then it suddenly started working. Could someone help me understand what's happening here as I know pointer management is an important concept and I think I understand what a pointer is and how it relates to memory, but I don't think I get why a single pointer does not get changed, whereas a double-pointer does.

谢谢!

推荐答案

在 C 中,函数的参数通过值传递.甚至指针也是按值传递的.

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

例如:

#include<malloc.h>
#include<stdio.h>
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;
}

如果您正在使用 linked list 并说例如,您想要修改头部.你将一个pointer to pointer(注意,它不被称为双指针)传递给头节点.

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.

这篇关于为什么以及何时需要双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆