[英]add a struct into struct linked list in C
我需要編寫從用戶(名稱、路徑和時間)獲取結構的軟件,然后將結構添加到鏈表的末尾。 我寫了兩個函數來解決它只在第一次運行時起作用的問題,如果用戶試圖向鏈接程序添加另一個結構程序崩潰):任何人都可以幫助我理解問題是什么嗎? 謝謝:這些是我創建的結構:
// 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;
}
問題就在這里——
if (list != NULL)
{
list = list->next;
}
list = tmp;
正確的是
while(list>next != NULL)
{
list = list->next;
}
list->next = tmp;
這將 go 到下一個直到最后一幀並添加新幀。 在您的代碼中,它第一次運行是因為它只執行 list=tmp。 對於其他時間,我們不會在列表末尾添加 tmp。 注意 if 而不是 while。 此外,在您的代碼中,當列表變為 NULL 時,我們丟失了最后一幀的地址,因此我們需要循環直到list>next!=NULL
而不是list!=NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.