I am experiencing problems on linked list with pointer variables inside the struct. Everytime when i insert a new visitor data, the previous visitors data will all be changed to the most current visitor data.
struct visitData{
char *SrNo;
char *ticketNo;
char *Name;
char *ID;
};
typedef struct ticket {
struct visitData visitor;
struct ticket *nextPtr;
}tick;
tick *addinfo(tick *previous,char* serial,char* ticketno,char* name,char* id)
{
tick *info = malloc(sizeof(tick));
info->nextPtr = NULL;
info->visitor.SrNo =serial;
info->visitor.ticketNo = ticketno;
info->visitor.Name = name;
info->visitor.ID=id;
if (previous != NULL)
{
previous->nextPtr = info;
}
printf("visitor info has been added: %s %s %s %s",info->visitor.SrNo,info->visitor.ticketNo,info->visitor.Name,info->visitor.ID);
return info;
}
CodePudding user response:
This should work:
#include <string.h>
tick *addinfo(tick *previous,char* serial,char* ticketno,char* name,char* id)
{
tick *info = malloc(sizeof(tick));
info->nextPtr = NULL;
info->visitor.SrNo = strdup(serial);
info->visitor.ticketNo = strdup(ticketno);
info->visitor.Name = strdup(name);
info->visitor.ID=strdup(id);
if (previous != NULL)
{
previous->nextPtr = info;
}
printf("visitor info has been added: %s %s %s %s \n",info->visitor.SrNo,info->visitor.ticketNo,info->visitor.Name,info->visitor.ID);
return info;
}
The problem was that you weren't allocating memory for your data. Also, be sure to free it when the program ends.