【问题标题】:add a struct into struct linked list in C在C中将结构添加到结构链表中
【发布时间】:2020-10-01 05:09:31
【问题描述】:

我需要编写从用户那里获取结构(姓名、路径和时间)的软件,然后将结构添加到链表的末尾。我写了两个函数来解决它只在第一次运行时才起作用的问题,如果用户试图向链接程序添加另一个结构,程序就会崩溃): 谁能帮我理解问题是什么? 谢谢! 这些是我创建的结构:

// Frame struct
typedef struct Frame
{
    char* name;
    int duration;
    char* path;

} Frame;


// Link (node) struct
typedef struct FrameNode
{
    Frame* frame;
    struct FrameNode* next;
} FrameNode;

有什么功能:

FrameNode* addFrame(Frame frame)
{
    FrameNode* p = malloc(sizeof frame);
    printf("*** Creating a new frame ***\n");
    printf("Please insert frame path:\n");
    p->frame->path = (char*)malloc(sizeof(char*) * 100);
    fgets(p->frame->path, 100, stdin);
    p->frame->path[strcspn(p->frame->path, "\n")] = 0;
    printf("Please insert frame duration <in miliseconds>:\n");
    scanf_s("%d", &(p->frame->duration));
    getchar();
    printf("Please chooce a name for a new frame:\n");
    p->frame->name = (char*)malloc(sizeof(char*) * 100);
    fgets(p->frame->name, 100, stdin);
    p->frame->name[strcspn(p->frame->name, "\n")] = 0;
    while (list != NULL)
    {
        while (strcmp(list->frame->name, p->frame->name) == 0)
        {
            printf("The name is already taken, Please enter another name\n");
            fgets(p->frame->name, 100, stdin);
        }
    }
    p->next = NULL;
    return p;
}

FrameNode* insertAtEnd(FrameNode* list, Frame fr)
{
    FrameNode* tmp = addFrame(fr);
    if (list != NULL)
    {
        list = list->next;
    }
    list = tmp;
    return list;
}

【问题讨论】:

  • 请提供minimal reproducible example 来证明您的问题。
  • insertAtEnd 没有将框架节点添加到列表的末尾。它将它添加为列表中的第一项或第二项,失去指向原始第二项(如果有)的链接。
  • 如果list != NULL 为真,addFrame 中的while (list != NULL) 循环将是一个无限循环。
  • @אבילוי 您的新版本 insertAtEnd 不会在列表中附加任何内容。它只是将添加的框架节点作为新列表返回。
  • addFrame 对其参数 frame 没有任何作用(除了评估 sizeof(frame) 无论如何都是不正确的)。

标签: c list struct


【解决方案1】:

问题就在这里-

if (list != NULL)
    {
        list = list->next;
    }
    list = tmp;

正确的是

while(list>next != NULL)
    {
        list = list->next;
     }
    list->next = tmp;

这将转到下一个直到最后一帧并添加新帧。在您的代码中,它第一次工作,因为它只执行 list=tmp。对于其他时间,我们不会在列表末尾添加 tmp。注意 if 而不是 while。 此外,在您的代码中,当列表变为 NULL 时,我们会丢失最后一帧的地址,因此我们需要循环直到 list&gt;next!=NULL 而不是 list!=NULL

【讨论】:

  • 好的,但是现在有另一个问题,我不能第三次走另一条路:这显示了这一行的错误:fgets (p-> frame-> path, 100,标准输入);错误:抛出异常:写访问冲突。 * (__ imp__malloc (...)) 为 nullptr
  • 看起来像一个单独的问题 - here
猜你喜欢
  • 2016-11-17
  • 2015-02-06
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
相关资源
最近更新 更多