我正在尝试在 c 中做人的链接列表。我所有的方法都有效,main()
直到我将它们放入 while 循环(用于读取用户的命令)。一切都可以编译,但是当我尝试运行它时,它会崩溃返回随机值。这是我的部分代码。
结构:
struct Person{
const char* name;
const char* sex;
int age;
struct Person* next;
} *head;
方法插入:
void insert(struct Person* h, char*n, char* s, int a){
for(; h->next != NULL; h=h->next){}
struct Person* p = (struct Person*) malloc(sizeof(struct Person));
p->name=n;
p->age=a;
p->sex=s;
p->next=NULL;
h->next=p;
}
和它不起作用的主要:
int main()
{
struct Person Maciek={"Maciek", "Male", 20, NULL};
head = &Maciek;
int comand = 0;
while(comand != 6){
printf("Choose command:\n 1-insert person \n 2-delete by index \n 3-delete by name \n 4-display by index \n 5-print whole list \n 6-exit\n");
scanf("%d", &comand);
if(comand == 1){
printf("Name, Gender, Age\n");
char* name;
char* sex;
int age;
scanf("%s, %s, %d", &name, &sex, &age);
printf("Name %s, Sex %s, Age %d", name, sex, age);
insert(head, name, sex, age);
}
if(comand == 2){
printf("2\n");
}
if(comand == 3){
printf("3\n");
}
if(comand == 4){
printf("4\n");
}
if(comand == 5){
printf("5\n");
}
}
return 0;
}
我对 C/C++ 很陌生,我非常感谢任何帮助。