本帖最后由 superbe 于 2020-5-7 23:22 编辑
char* name;
name成员只是一个char *的指针,而你并没有给输入的名字字符串分配内存空间。
这是修改过的代码,包括其它一些修改。#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define LEN sizeof(struct general) //general结构的大小
#define NLEN 30 //名字最大长度
struct general *creatList(); //创建链表;
void printList(struct general* head); //打印列表
struct general
{
char* name;
int force;
int intelligence;
struct general *next; //指向下一节点
};
int n = 0;
struct general *creatList() //创建链表
{
struct general *head = NULL;
struct general *p1, *p2;
char sname[NLEN];
printf("Enter the name: ");
scanf("%s", sname);
while (strcmp(sname, "over") != 0)
{
p1 = (struct general *)malloc(LEN);
p1->name = (char *)malloc(strlen(sname) + 1); //删除节点时要释放分配的内存
strcpy(p1->name, sname);
printf("Enter the force: ");
scanf("%d", &p1->force);
printf("Enter the intelligence: ");
scanf("%d", &p1->intelligence);
p1->next = NULL;
if (n == 0)
head = p1;
else
p2->next = p1;
p2 = p1;
n++;
printf("\nEnter the name: ");
scanf("%s", sname);
}
return head;
}
void printList(struct general* head)
{
struct general* pMove;
pMove = head;
while (pMove)
{
printf("name:%s 武力:%d 智力:%d\n", pMove->name, pMove->force, pMove->intelligence);
pMove = pMove->next;
}
printf("总人数 = %d\n", n);
}
int main()
{
struct general *gen;
gen = creatList();
printList(gen);
system("pause");
return 0;
}
|