file - C programming, fscanf only inputs the last element -


i'm trying multiple elements file , put in array linked list inputs last element of file.

inside file is

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19  

here's code

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;         }     } } 

the expected output should be

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 

but

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 

i trying put elements in indexes corresponding ones digit, puts last element 19.

you call malloc single time end situation elements in array points same object. instead should call malloc each succesful scan.

like:

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 loop             temp = elem % 10;      // find index new object shall added             tempstruct->elem = elem;             tempstruct->next = a[temp];             a[temp] = tempstruct;         }     } } 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -