gpt4 book ai didi

c - C语言中如何比较指针值与NULL

转载 作者:行者123 更新时间:2023-11-30 18:42:48 24 4
gpt4 key购买 nike

我正在编写一个函数,该函数删除链表中的一个节点,其输入是指向链表的指针。如果函数删除一个只有一个节点的链表,函数将使指针指向NULL。这是部分代码:

void remove(dlinkNode_t *start){
//some previous code
if(start->next==NULL){//meaning we're removing the head of the linked list
dlinkNode_t current=start; //get a temp pointer to point at this node
start=NULL; //make start point to null
free(current); //free the head
return;
}
// More code

在 main 中,我创建了一个包含一个节点的链表,并将该链表传递给删除函数以释放它。代码如下:

int main(){
dlinkNode_t *node1=create(); //creates a node and make node1 point at it
remove(node1); //now node1 should point at NULL
if(node1==NULL)
printf("hi");
return 0;
}

但我没有看到 hi 打印出来。我不知道为什么 if 语句没有通过。有任何想法吗?

最佳答案

remove 的本地范围内创建了指针的新副本。您对指针所做的任何更改仅在该范围内可见。对指针所指向的值所做的任何更改都将返回到调用范围。

您可以通过以下两种方法之一解决此问题:

  • 返回编辑后的指针

    node1 = remove(node1); 

    并在删除中进行更改。

    dlinkNode_t * remove(dlinkNode_t *start){
    //some previous code
    //Function code
    return start;
  • 或者您可以将指针传递给指针 start,然后操作该指针。

    函数调用:

    remove(&node1);

    函数定义:

    void remove(dlinkNode_t **start){
    //some previous code
    if((*start)->next==NULL){ // meaning we're removing
    // the head of the linked list
    dlinkNode_t current=**start; //get a temp pointer
    // to point at this node
    **start=NULL; //make start point to null
    free(current); //free the head

关于c - C语言中如何比较指针值与NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com