【发布时间】:2021-10-18 21:40:00
【问题描述】:
为什么这段代码会为链表中的所有节点输出相同的名称?
程序输出
Insert number of users :
4
Mike
John
Bob
Alice
Name : Alice @ Pointer :0x874ae0
Name : Alice @ Pointer :0x874b00
Name : Alice @ Pointer :0x874b20
Name : Alice @ Pointer :(nil)
此代码背后的想法是获取x 的用户名数量并创建一个链表,然后循环该链表并打印每个名称以及下一个名称的指针。
typedef struct node
{
char *name;
struct node *next;
} node;
int main(void)
{
int x;
printf("Insert number of users :\n"); // capture int from user
scanf("%i", &x);
char str[LENGTH];
node *n = malloc(sizeof(node));
if (n == NULL)
return 1;
node *start = n; // pointer to the start of the linked list
// loop for n times to capture names
for (int i = 0; i < x; i++)
{
scanf("%s", str); // capture string
n->name = str;
// reached end of loop
if (i == x-1)
n->next = NULL;
else
n->next = malloc(sizeof(node));
n = n->next;
}
for (node *tmp = start; tmp != NULL; tmp = tmp->next)
{
printf("Name : %s @ Pointer :%p\n", tmp->name, tmp->next);
}
return 0;
}
一个简单的脚本,用于获取人名并将其插入到链表中。
【问题讨论】:
-
n->name = str;- 这会将相同的str分配给所有节点。你需要为每一个分配新的内存 -
n->name = str;-->n->name = strdup(str); -
永远不要使用
scanf("%s",str);永远。如果不限制输入字符串长度并且不检查返回值,则存在缓冲区溢出的风险,这也会在scanf()失败时导致UB。
标签: c for-loop linked-list dynamic-memory-allocation c-strings