I'm attempting to input multiple times to a char pointer in linked list using scanf
. but every time I enter new input the name
changes in all the fields.
here is my linked list:
struct node {
struct node *next;
int level;
char *name;
};
here is my main function:
struct node *root = NULL;
while (1) {
char arrays[12];
char *n;
n = arrays;
int i = NULL;
printf("Enter level: ");
scanf("%i", &i);
printf("\nEnter name: ");
scanf("%s", arrays);
insert(&root, i, n, compare);
display(root);
}
insert function:
void insert(struct node **head, const int level, char *name, int(*cmp)(struct node *l, struct node *r))
{
struct node *new;
new = malloc(sizeof *new);
new->level = level;
new->name = name;
/* Find the insertion point */
for (; *head != NULL; head = &(*head)->next)
{
if ((*head)->level > level || (*head)->level == level && cmp(*head, new) > 0) { break; }
}
new->next = *head;
*head = new;
}
basically if I input:
input: | expected output: | actual output:
1 smith | 1 john | 1 alice
1 john | 1 smith | 1 alice
3 malek | 2 alice | 2 alice
2 alice | 3 malek | 3 alice
note: the functions are working as expected when I'm entering data manually without scanf
eg:
insert(&root, 1, "Abbas", compare);
insert(&root, 1, "Calbass", compare);