【问题标题】:I'm making a linked list of strings in C, and having a problems我正在用 C 制作一个字符串的链接列表,但遇到了问题
【发布时间】:2021-06-11 11:21:15
【问题描述】:

我是编程初学者。谢谢你帮助我。

我正在尝试在字符串中创建一个链接列表。 输入是字符串,如果输入是“退出”则结束。 但是当我编译它时,它只打印出最后的输入,我无法解决它! 从函数addrear中区分数据是否第一次存储在链表中。并适当地存储数据和链接到另一个节点。 从函数printlist开始,从链表的开头开始,打印出每个节点的数据。

我用整数类型尝试过,当这段代码用 int 而不是 string 执行时,它工作正常,所以我认为错误来自字符数组。

例如)输入1“转储”,
输入2“结束”,
输入3“目录”,
input4 "退出",

输出会是

转储, 结尾, 目录, 退出

但它出来了

退出 出口 出口 退出


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char instruction[1000];

struct Node {
    struct Node* next;
    char* data;
};

struct Node* pStart = NULL;
struct Node* pEnd = NULL;

void addrear(char* val)
{
    struct Node* Current;
    Current = (struct Node*)malloc(sizeof(struct Node));
    Current->data = val;
    Current->next = NULL;
    //printf("%s\n", Current->data);
    if (pStart == NULL)
    {
        pStart = Current;
        pEnd = Current;
    }
    else
    {
        pEnd->next = Current;

        pEnd = Current;
    }
}
void printlist(struct Node* Current)
{
    Current = pStart;
    while (Current != NULL)
    {
        printf("%s\n", Current->data);
        Current = Current->next;
    }
}
int main()
{
    int i;

    while (1)
    {

        printf("sicsim> ");
        fgets(instruction, sizeof(instruction), stdin);
        instruction[strlen(instruction) - 1] = '\0';
        addrear(instruction);

        if (strcmp(instruction, "exit") == 0)
        {
            break;
        }
    }
    printlist(pStart);


}

【问题讨论】:

  • 't prints out last inputs only' 明白了...
  • “链表”标签下有一些 (!) 重复项。

标签: c string data-structures linked-list


【解决方案1】:

正如 MZB 回答的那样,您的问题是您混淆了参考和价值。

你说: “我用 integer 类型尝试过,当这段代码用 int 而不是 string 执行时,它工作正常,所以我认为错误来自字符数组。”

分配int 的值和分配字符串之间存在巨大差异。无论如何,你都会得到这个int 的价值——你不在乎他“住在哪里”。当我们谈论 char 时也是如此,但如果您谈论字符串 - 您希望 point 指向此字符串 - 所以您希望指向某个可以保存您的数据并且不会修改。

如果你想保存这个字符串你需要知道这个字符串存储的地方不会被访问。

因此,您应该逐个字符地复制字符,这样您就不会关心“指令”是否会被分配为其他内容。

【讨论】:

  • 感谢您的建议,我通过在 addrear func 中创建新的 char 数组来更改代码,并一个一个地存储每个字符。并将新的 char 数组链接到链表中。它在 Visual Studio 中运行良好。但是我正在用腻子制作一个 sic 机器外壳,所以我在腻子中尝试了它。但它在 Putty 中只打印出空白......
【解决方案2】:

您的错误是您在 Node 结构中存储了指向指令缓冲区的指针。每次读取字符串时,都会用读取的字符串覆盖该缓冲区。

你需要为每个字符串分配内存。

如果您正在学习 C++,请查看有关“新”的文档(您应该如何为 Node 分配空间等)malloc 是一种较低级别的 C 处理方法。

【讨论】:

  • 你为什么提到 C++ 的东西?这是一个关于 C 的问题。特别是因为您在现代 C++ 中很少使用 new
  • 感谢您的建议,我修改了代码,并在 Visual Studio 中成功了。但是当我在 Putty 中执行此操作时,它现在只打印出空格..
猜你喜欢
  • 2021-09-26
  • 2021-01-10
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多