gpt4 book ai didi

c - 在 C 中打印列表的元素

转载 作者:行者123 更新时间:2023-11-30 20:11:29 25 4
gpt4 key购买 nike

基本上在下面的代码中,我尝试在列表中插入一些名字和一些年龄并将它们打印出来。但是,我的程序仅打印列表的姓氏和年龄。有什么建议吗?

#include <stdio.h>
#include <stdlib.h>
/* these arrays are just used to give the parameters to 'insert',
to create the 'people' array
*/

#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};

typedef struct person
{
char *name;
int age;
struct person *next;
}Person;

Person *headp = NULL;
static Person* insert(Person *p, char *name, int age)
{
p = (Person*)malloc(sizeof(Person));
if (p == NULL)
abort();
p->name = name;
p->age = age;
p->next = headp;
return p;
}

int main(int argc, char **argv)
{
Person *people=headp;
for (int i = 0; i < 7; i++)
{
people = insert (people, names[i], ages[i]);
}
while (people != NULL)
{
printf ("name: %s, age: %i\n", people->name, people->age);
people= people->next;
}
return 0;
}

最佳答案

您正在使用 malloc 返回的地址覆盖传递的变量 p (内存泄漏,并且您丢失了之前的头),更改为:

static Person *insert(Person *head, char *name, int age) 
{
Person *p = malloc(sizeof(Person)); /* Don't cast malloc */

if (p == NULL)
abort();
p->name = name;
p->age = age;
p->next = head;
return p;
}

关于c - 在 C 中打印列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40562915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com