如何在C中比较指针值与NULL
我正在编写一个函数,该函数删除链表中的一个节点,该节点的输入是指向链表的指针。如果函数删除只有一个节点的链表,该函数将使指针指向NULL。以下是部分代码:如何在C中比较指针值与NULL,c,C,我正在编写一个函数,该函数删除链表中的一个节点,该节点的输入是指向链表的指针。如果函数删除只有一个节点的链表,该函数将使指针指向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=star
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
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;
}
在main中,我创建了一个带有一个节点的链表,并将此链表传递给remove函数以释放它。代码如下:
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
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;
- 或者,您可以将指针传递到指针开始处,然后操纵该指针
函数调用:
功能定义: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