简体   繁体   English

在 C 的 struct 链表中添加一个 struct

[英]add a struct into struct linked list in C

I need to write software that gets structure from the user (name, path and time) and then add the structure to the end of a linked list.我需要编写从用户(名称、路径和时间)获取结构的软件,然后将结构添加到链表的末尾。 I wrote two functions that work the problem that it only works in the first run, if the user tries to add another structure to the linked program the program crashes): Can anyone help me understand what the problem is?我写了两个函数来解决它只在第一次运行时起作用的问题,如果用户试图向链接程序添加另一个结构程序崩溃):任何人都可以帮助我理解问题是什么吗? Thank you: These are the structures I created:谢谢:这些是我创建的结构:

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

} Frame;


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

What are the functions:有哪些功能:

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;
}

The problem is here-问题就在这里——

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

Correct one is正确的是

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

This will go to next until the last frame and add the new frame.这将 go 到下一个直到最后一帧并添加新帧。 In your code, it works first time because it only executes list=tmp.在您的代码中,它第一次运行是因为它只执行 list=tmp。 For other times, we are not going to the end of the list to add tmp.对于其他时间,我们不会在列表末尾添加 tmp。 Note if instead of while.注意 if 而不是 while。 Also, in your code when list becomes NULL, we lose address of last frame, so we need the loop till list>next!=NULL instead of list!=NULL .此外,在您的代码中,当列表变为 NULL 时,我们丢失了最后一帧的地址,因此我们需要循环直到list>next!=NULL而不是list!=NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM