C编程,fscanf仅输入最后一个元素

C编程,fscanf仅输入最后一个元素,c,file,linked-list,C,File,Linked List,我试图从一个文件中获取多个元素并将其放入数组链表中,但它只输入文件的最后一个元素 文件里面是 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 这是我的密码 typedef struct node{ int elem; struct node *next; }node; void insert(node **a) { int temp,elem; node *tempstruct; tempstruct

我试图从一个文件中获取多个元素并将其放入数组链表中,但它只输入文件的最后一个元素

文件里面是

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
这是我的密码

typedef struct node{
    int elem;
    struct node *next;
}node;

void insert(node **a)
{
    int temp,elem;
    node *tempstruct;
    tempstruct = (*node)malloc(sizeof(struct node));
    FILE *fp;
    if(fp = fopen("input.txt","r")){
        while(fscanf(fp,"%d",&elem)==1){
            temp = elem%10;
            tempstruct->elem = elem;
            tempstruct->next = a[temp];
            a[temp] = tempstruct;
        }
    }
}
预期输出应为

A[0]   10
A[1]   11   1
A[2]   12   2 
A[3]   13   3 
A[4]   14   4
A[5]   15   5 
A[6]   16   6
A[7]   17   7
A[8]   18   8
A[9]   19   9
但我得到的是

A[0]   19
A[1]   19
A[2]   19
A[3]   19
A[4]   19
A[5]   19
A[6]   19
A[7]   19
A[8]   19
A[9]   19
我试图将元素放入对应于其一位数的索引中,但它只放入最后一个元素,即19。

您只调用了一次malloc,因此数组中的所有元素都指向同一个对象。相反,您应该为每次成功扫描调用malloc

比如:


你的代码无法编译。例如*节点,温度=%elem;尽量避免类型转换malloc的返回值。您尝试调试的次数太多了。首先,了解如何从文件中读取数据。第二,找出如何将这些项分配给节点的soops抱歉,它的temp=elem%10要获取一个digitsCode的索引是不可靠的:不清楚[]的数量有多大是有效的。@chux True。不幸的是,OP从未发布过完整的代码示例。然而,从预期输出来看,似乎可以公平地假设[]有10个元素,即10个链表,其中数据根据数据的最后一位进行排序。
void insert(node **a)
{
    int temp,elem;
    node *tempstruct;
    FILE *fp;
    if(fp = fopen("input.txt","r")){
        while(fscanf(fp,"%d",&elem)==1){
            tempstruct = malloc(sizeof(struct node));  // malloc inside the loop
            temp = elem % 10;      // Find the index where the new object shall be added
            tempstruct->elem = elem;
            tempstruct->next = a[temp];
            a[temp] = tempstruct;
        }
    }
}