为何以及何时需要双指针? [英] why and when is a double-pointer required?
问题描述
我一直是一个系统管理员,我大部分的生活,但最近决定练习一些我开发的知识和尝试DEVOPS位置。我有这样练了一些C和Python技能,写了一些code插入一个数字,一个链表。
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;
}
如果您正在使用链表
s工作,并比方说,你要修改的头。您将通过 A 指针指针(需要注意的是,它不称为双指针)
头节点
。
If you are working with linked list
s 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屋!