打印链接列表时出错

时间:2017-10-25 15:05:57

标签: c linked-list

我创建了链接列表来存储员工ID和名称。

当我尝试打印它时,它只显示id而不是员工姓名,我还想在用户输入-1时退出程序而不询问名称,只需退出程序并显示id和名称i我目前正在使用devC ++来编译我的代码

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
    int id;
    char name[20];
    struct node *next;
};

struct node *create()
{
    struct node *p, *r, *n;
    int s, k;
    char name[20];
    s = sizeof(struct node);
    printf("Linked List\n");
    printf("Enter id:");
    scanf("%d", &k);
    printf("Enter name:");
    scanf("%s", name);
    p = r = NULL;
    while(k!=-1)
    {
        n = (struct node *)malloc(s);
        n->id = k;
        n->next = NULL;
        if(r == NULL)
            r = n;
        else
            p->next=n;
        p=n;
        printf("Enter the Id or-1 to stop:");
        scanf("%d", &k);
        printf("Enter the name ");
        scanf("%s", name);
    }
    return(r);      
}

void display(struct node *r)
{
     printf("\nId             Name \n");
     while(r != NULL)
     {
         printf("\n %d", r->id);
         printf("\n %s", r->name);
         r = r->next;    
     }
}

int main()
{
    struct node *ptr;
    ptr = create();
    display(ptr);
}

1 个答案:

答案 0 :(得分:0)

您实际上是在name变量中读取的,但是您不会在结构中移动它。 也就是说,你可以直接读入你分配的结构,但是当用户输入太大(超过19个字符)时,棘手的部分就是不要溢出缓冲区。

这可能是这样的:

#include<stdio.h>
#include<stdlib.h>
struct node {
    int id;
    char name[20];
    struct node *next;
};

struct node *create(void) {
    struct node *p, *r;
    printf("Linked List\n");
    p = r = NULL;
    while (1) {
        int id;
        printf("Enter the Id or-1 to stop:");
        scanf("%d", &id);

        if (id == -1)
            break; // user asked to leave

        struct node *n = malloc(sizeof(*n));
        // if (n == NULL) exit(-1); as you prefere...
        n->id = id;
        printf("Enter the name ");
        // careful of buffer overflow here
        scanf("%19s%*[^\n]", n->name);
        n->next = NULL;

        if (r == NULL)
            r = n;
        else
            p->next = n;
        p = n;
    }
    return r;
}

void delete(struct node *r) {
    while (r != NULL) {
        struct node *n = r;
        r = r->next;
        free(n);
    }
}

void display(const struct node *r) {
    printf("\nId             Name \n");
    while (r != NULL) {
        printf("%d         %s\n", r->id, r->name);
        r = r->next;
    }
}

int main(int argc, char **argv) {
    struct node *ptr = create();
    display(ptr);
    delete(ptr);
    return 0;
}

作为奖励,我还添加了免费部分,以便您不会泄漏。