【发布时间】:2021-02-03 20:47:19
【问题描述】:
我正在尝试在 C 中实现一个链表:
struct Node{
struct Node *next;
void *data;
};
带有插入功能:
void insert(void *p2Node, void *data)
{
struct Node *newNode;
struct Node **p2p2Node= (struct Node **)p2Node;
if (newNode = malloc(sizeof(struct Node))) /* if successfully allocated */
{
newNode->data = data;
if ((*p2p2Node) != NULL) /* if the list is not empty */
{
newNode->next = (*p2p2Node)->next;
(*p2p2Node)->next = newNode;
}
else
(*p2p2Node) = newNode;
p2Node = p2p2Node;
}
printf("Inside the insert: %s\n", (*p2p2Node)->data);
}
我在main()中调用了insert:
int main()
{
char *setA = "liquid ";
char *setB = " lgd";
char *setC = "sample";
struct Node *nList = malloc(sizeof(struct Node));
insert(nList, setC);
printf("2Get %s\n", nList->data);
return 0;
}
未报告错误或警告,但值仅在 insert 内更改。回到main(),链表还是空的。
我不明白:main() 中的nList 是一个空指针。 insert()里面,*p2Node没有改,我用p2p2Node改了p2Node指向的值,为什么不行?我的指针不匹配吗?有没有办法在不修改insert()的参数的情况下让它工作?
谢谢。
【问题讨论】:
-
您不能只强制转换一个参数来假装它是通过引用传递的。我参考这一行:
struct Node **p2p2Node= (struct Node **)p2Node;如果你想让函数修改指针的值,那么函数的参数必须是指向指针的指针. -
@paddy 这是否意味着我应该将传入的指针(即
nList)修改为指向结构的指针?我的意思是,指向指针的指针仍然是指针,应该可以像void *p2Node一样传入insert? -
根据我在函数内部看到的逻辑,函数的签名应该是
void insert(struct Node **p2p2Node, void *data),当你为空列表调用它时,nList应该是 NULL。然后调用insert(&nList, setC);在insert函数内部进行分配时,还应该使用calloc,OR 将next显式设置为NULL。目前,插入的第一个节点上的 next-pointer 的值是未定义的。
标签: c function struct linked-list