I have the following structure and function that adds things to the structure:
struct scoreentry_node {
struct scoreentry_node *next;
int score;
char* name;
}
;
typedef struct scoreentry_node *score_entry;
score_entry add(int in, char* n, score_entry en) {
score_entry r = malloc(sizeof(struct scoreentry_node));
r->score = in;
r->name = n;
r->next = en;
return r;
}
i have input that take it in the following main file:
int score;
char name[];
int main(void) {
score_entry readin = NULL;
while(1)
{
scanf("%s%d", name, &score);
readin = add(score, name, readin);
// blah blah
I dont know why but when input a name it gets added to readin, but when i input another name all the names in readin have this new name
for example:
input:
bob 10
readin = 10 bob NULL
jill 20
readin = 20 jill 10 jill NULL
I dont know why bob disappears… any reason why it does that ?
You’re just storing a pointer to the name string, not a copy of the string itself. Try using
strdup:Just be sure to
free(r->name)when freeing a node.An alternative would be to change
char* nametochar name[1], and do something like this:This saves allocating a separate chunk of memory for the string, but note that in that case
namemust be at the end of your structure.