[英]linked list char pointer scanf input
I'm attempting to input multiple times to a char pointer in linked list using scanf
. 我试图使用scanf
向链表中的char指针多次输入。 but every time I enter new input the name
changes in all the fields. 但是每次我输入新输入时, name
在所有字段中更改。
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: 注意:当我不使用scanf
手动输入数据时,这些功能将按预期运行,例如:
insert(&root, 1, "Abbas", compare);
insert(&root, 1, "Calbass", compare);
This line: 这行:
new->name = name;
just change the value of pointer - it does not copy a string. 只需更改指针的值-它不会复制字符串。 So all elements in the linked list will point to arrays
. 因此,链表中的所有元素都将指向arrays
。 So changing the contents of arrays
will make it look as if all elements in the list was changed (but they wasn't). 因此,更改arrays
的内容将使其看起来好像列表中的所有元素都被更改了(但没有更改)。
You probably need: 您可能需要:
strcpy(new->name, name); strcpy(new-> name,name);
and then you need to malloc
memory for the string as well. 然后你需要malloc
内存的字符串为好。
Something like: 就像是:
new = malloc(sizeof *new);
new->level = level;
new->name = malloc(12 * sizeof(char)); // Memory for the string
strcpy(new->name, name); // Copy the input string
BTW: 顺便说一句:
Change 更改
insert(&root, i, n, compare);
to 至
insert(&root, i, arrays, compare);
and remove the n
variable. 并删除n
变量。 The functionality is the same but the coder is easier to read and understand. 功能相同,但编码器更易于阅读和理解。
Look like you're inserting a pointer to arrays
into the list. 看起来您正在将指向arrays
的指针插入列表中。 When you write: 当你写:
insert(&root, 1, "Abbas", compare);
it's work because nothing modify the string literal "Abbas", but arrays
's content is overwritten every time the scanf("%s", arrays);
之所以有效,是因为没有任何修改字符串文字“ Abbas”的方法,但是每次scanf("%s", arrays);
时,都会覆盖arrays
的内容scanf("%s", arrays);
is executed. 被执行。 Consider changing char* name to char name[12] and reading input directly into the node. 考虑将char *名称更改为char name [12]并将输入直接读入节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.