0
目前,我正在尝试编写链表,但遇到问题。 当我执行下面的代码,它只是打印分配新节点后,根节点的值(空值)没有改变
当前状态:
于是我就用GDB,发现当我分配“iHead = newNode”,并返回到主,头的值没有改变! 问题是相对于通过价值/参考或任何其他?
#include <stdio.h>
#include <stdlib.h>
typedef struct node *nodePtr;
struct node{
int value;
nodePtr next;
};
void print(nodePtr);
void insert(nodePtr, int);
int main(void){
nodePtr head = NULL;
insert(head, 1);
insert(head, 2);
insert(head, 3);
insert(head, 4);
insert(head, 5);
print(head);
return 0;
}
void print(nodePtr iHead){
nodePtr ptr = iHead;
printf("Current state:");
while(ptr){
printf("%d ", ptr->value);
ptr = ptr->next;
}
printf("\n");
}
void insert(nodePtr iHead, int iValue){
nodePtr newNode;
newNode = (nodePtr) malloc(sizeof(struct node));
newNode->value = iValue;
newNode->next = NULL;
if(iHead == NULL)
iHead = newNode;
else{
//find the last node
nodePtr ptr = iHead;
while(ptr -> next)
ptr = ptr->next;
//append new node
ptr -> next = newNode;
}
}
欢迎来到Stack Overflow。请尽快阅读[关于]页面。您需要将'nodePtr *'传递给插入函数,以便它可以覆盖调用函数中的指针。或者,插入函数需要返回新的根节点:'node ='insert(nodePtr root,int value)''调用像'head = insert(head,3);'。这是一个非常普遍的问题;还有许多其他问题同构于这个问题,答案在于两种选择之一。 – 2015-02-05 18:02:01
C是按值拨打的。在函数中更改函数参数不会在调用方中修改它。 – EOF 2015-02-05 18:03:19