C语言 链表没有正确输出


#include<stdio.h>
#include<stdlib.h>
void line_add(struct Line *p);

void line_get(struct Line *p);

struct Line
{
    char sentence[128];
    char role[16];
    struct Line *next;
};

void line_add(struct Line **p_add)
{
    struct Line *p_new = (struct Line *)malloc(sizeof(struct Line));
    line_get(p_new);
    *p_add = p_new;
    p_new->next = *p_add;
}

void line_get(struct Line *p_get)
{
    printf("请输入台词:\n");
    scanf("%s",p_get->sentence);
    printf("请输入角色:\n");
    scanf("%s",p_get->role);
    printf("%s:“%s”\n",p_get->role,p_get->sentence);
}    

int main(void)
{
    struct Line *p = NULL;
    int flag = 1;
    while(flag)
    {
        line_add(&p);
        printf("你还要输入台词吗?(0或1)\n");
        scanf("%d",&flag);
    }
    int count = 0;
    while(p != NULL)
    {
        printf("%d -- %s:“%s”\n",++count,p->role,p->sentence);
        free(p);
        p = p->next;
    }
    return 0;
}

运行后,输入和输出如下:

img

因为你的next指针没有返回,导致你的指针p一直不变,所以总是在给同一项赋值
而p_new->next = *p_add其实就是把下一项指向了这一项,除了增加一项之外,并没有增加内容
当你不断调用next的时候,其实陷入了无限递归
还好你写了个free(p),当p被释放了的时候,才能停下来