c - 打印链表时结构变量没有被正确保存?

标签 c switch-statement

我有一个链表,我正在尝试插入一个新节点,这似乎成功地将节点插入了我想要它去的地方,但变量总是以 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/

相关文章:

c - 列出链接列表的内容

c - 更新 CSV 文件中的数据

c++ - 如何实现通用 switch/case,它也适用于一般 C++ 类型并且语法相似?

java - java中的switch语句接受哪些数据类型

c - 以下代码有什么问题?

c - 将另一个文件中的函数添加到项目需要修改 makefile 吗?

c++ - 是否有任何设计模式可以避免嵌套的开关盒?

java - 打开 if 语句?

c - 尝试在 XCode 中编写基本的 C 程序,但我一直收到错误提示 'Expected expression'

ios - 如何从 .c 文件向 swift 类发送通知或委托(delegate)回调?