I’m trying to append a struct object to a linked list. The data is read from stdin. The int attribute gets appended correctly, but all char * values previously appended keep getting replaced by the new input.
My append and getElement functions work properly for string inputs.
Here is my code:
#include "List.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct EventObj{
char *name;
int time;
} EventObj;
typedef EventObj* EventPtr;
void add(ListPtr a, EventObj *event);
void printTime(ListPtr a);
int main(int argc, char **argv) {
ListPtr a1 = newList(0, NULL, NULL);
char func[10], agenda[256], eventName[256], buffer[256];
int time;
printf("%s\n", "Begin reading inputs and appending events");
while(fgets(buffer, 256, stdin) != NULL){
sscanf(buffer, "%s %s %s %d", func, agenda, eventName, &time);
EventPtr event = malloc(sizeof(*event));
event->time = time;
event->name = eventName;
printf("%d ", event->time);
printf("%s\n", event->name);
appendList(a1, event);
}
printf("%s\n", "Print from the list after appending");
printTime(a1);
}
void printTime(ListPtr a){
for (int i=0; i <length(a); i ){
EventPtr cur = getElement(a, i);
printf("%d ", cur->time);
printf("%s\n", cur->name);
}
}
Output:
Begin reading inputs and appending events
9 event1
10 event2
12 event3
8 event4
Print from the list after appending
9 event4
10 event4
12 event4
8 event4
// this should be event1 event2 event3 event4
Append function:
bool appendList( ListPtr L, void *data ){
if(L == NULL){
printf("%s", "appendList: NULL List");
return false;
}
NodePtr node = newNode(data);
if(node == NULL){
printf("%s", "appendList: NULL Node");
return false;
}
node-> next = L -> head;
L -> head = node;
L ->length ;
return true;
}
getElement:
void *getElement( ListPtr L, int i){
if(L == NULL || i > L->length){
printf("%s", "delElement: No entry or List found\n");
return NULL;
}
NodePtr tmp = L-> head;
i = L->length - i - 1;
while(tmp != NULL && i > 0){
tmp = tmp -> next;
i --;
}
return tmp -> data;
}
CodePudding user response:
After this statement
event->name = eventName;
in the while loop
while(fgets(buffer, 256, stdin) != NULL){
the pointer name
points to the same array eventName
. So the last string that was stored in the array eventName
is shown for all nodes because all nodes point to this array.
You need dynamically to allocate memory for a character array in each node and copy the string stored in the array eventName
in this dynamically allocated array.