我有一个链表,我正在尝试插入一个新节点,这似乎成功地将节点插入了我想要它去的地方,但变量总是以 NULL 出现。有人能指出我是在哪里导致这种情况发生的吗?
这里是打印插入的方法。
void printList(node *head)
{
node *p;
p = head;
if(p->next == NULL)
printf("No stops currently in the tour.");
else
{
while(p->next != NULL)
{
printf("Tour Stop: %s - Description: %s\n", p->name, p->name);
p = p->next;
}
}
}
void insertInOrder(node *head, node *newNode)
{
printf("What is the stop you want the new stop to come after? Type 'end' to insert at the end of the tour.");
char key[100];
scanf("%s", &key);
getchar();
node *p;
p = head->next;
if(head->next == NULL)
head->next = newNode;
else if(key == "end")
{
while(p->next != NULL)
p = p->next;
p->next = newNode;
printf("\nAT 57, newNode->info = %s and newNode->name = %s", newNode->info, newNode->name);
}
else
{
while(strcmp(p->name, key) != 0)
{
if(p->next == NULL)
{
printf("Couldn't find the tour stop you requested, inserting at end of tour.");
break;
}
p = p->next;
}
p->next = newNode;
}
这是我用来传递给插入方法的 createNewNode 方法
node* createNewNode()
{
node *newNode;
newNode = malloc(sizeof(struct node));
printf("Enter the name of the new tour stop.\n");
char newName[100];
fgets(newName, sizeof(newName), stdin);
newNode->name = newName;
printf("Enter information about the tour stop. Max number of characters you can enter is 1000.\n");
char newDescription[1000];
newNode->info = newDescription;
fgets(newDescription, sizeof(newDescription), stdin);
return newNode;
}
最佳答案
您没有将字符串复制到结构中。您只是将指针复制到 createNewNode()
中的局部变量:
char newName[100];
fgets(newName, sizeof(newName), stdin);
newNode->name = newName;
这意味着当您稍后访问该存储的指针时出现未定义的行为,因为它不再有效。
您需要在结构内有字符空间,并复制(或只读取)其中的字符串,以便只要节点存在,它就会一直分配。
关于c - 打印链表时结构变量没有被正确保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19784597/