C上的链表与结构

C上的链表与结构,c,struct,linked-list,C,Struct,Linked List,我正在尝试使用链表制作一个清单程序,但是当我想显示我输入的数据列表时,我遇到了一个问题。 这是输入数据的代码: #include <stdio.h> #include <stdlib.h> #include <malloc.h> struct t_barang { char kode[9]; char nama[30]; int harga; int stok; }; struct l_barang { struct t_

我正在尝试使用链表制作一个清单程序,但是当我想显示我输入的数据列表时,我遇到了一个问题。 这是输入数据的代码:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

struct t_barang
{
   char kode[9];
   char nama[30];
   int  harga;
   int  stok;
};

struct l_barang
{
   struct t_barang item;
   struct l_barang *next;
};

int main(){
    typedef struct l_barang *p_barang;
    struct l_barang *head;
    head=NULL;
    int jumlah=0;
    do{
        printf("Input Jumlah barang = ");
        scanf("%d", &jumlah);
        if(jumlah == 0)
            break;
        else{
            struct l_barang *baru = (struct l_barang*) malloc(sizeof(struct l_barang));
            printf("Input Kode barang = ");
            scanf("%s", &(baru->item).kode);
            printf("Input nama barang = ");
            scanf("%s", &(baru->item).nama);
            printf("Input harga barang = ");
            scanf("%d", &(baru->item).harga);
            baru->item.stok=jumlah;
            if(head == NULL){
                baru->next=NULL;
                    head=baru;}
            else{
                struct l_barang *tail;
                    tail=head;
                        while(tail->next != NULL){
                tail->next=NULL;
                tail = baru;
                }
            }
        }
    }
    while(jumlah != 0);
p_barang tampil = head;
    while(tampil){
        printf("%d\t%s\t%s\t%d\n",tampil->item.stok, tampil->item.kode, tampil->item.nama, tampil->item.harga);
    tampil=tampil->next;}

谢谢大家!

问题可能来自这里:

            tail=head;
            while(tail->next != NULL){
              tail->next=NULL;
              tail = baru;
            }
如果
tail->next
不为NULL,请将其设置为NULL,然后更改
tail
:这将触发内存泄漏和其他问题

通常的做法是:

            tail=head;
            while(tail->next != NULL){
              tail=tail->next;
            }
            //tail is now the end of the list

            tail->next = baru;
            baru->next=NULL;
            //now, baru is the end of the list

但问题是什么?请不要让/期望人们阅读您的代码、调试代码并报告解决方案。问题是,当我输入数据时显示的只是我输入的第一个数据,它无法显示第二个数据和其他数据。在进行任何调试的地方,几乎不可能找到任何链表问题。这似乎是某种不成文的法则,链表开发者无法调试,因此被迫将代码转储到链表上。