尽管我将malloc更改为每个结构的成员,但是在输入成员之前它将关闭。我认为这是一个内存问题,但我不知道我在哪里犯了错误。
struct player {
int num;
char name[40];
int age;
int Amatch;
int goals;
struct player* next;
};
这是结构代码。
printf("Enter the number of players: ");
scanf("%d",&player_num);
ptr = (struct player*)malloc(sizeof(struct player));
if (ptr == NULL) {
printf("Error!");
return 0;
}
ptrW = ptr;
ptrWW = ptr;
for (int j = 0; j < player_num; j++) {
if (j != 0) {
ptr = (struct player*)malloc(sizeof(struct player));
if (ptr == NULL) {
printf("Error!");
return 0;
}
}
ptr->num = (int*)malloc(sizeof(int));
if (ptr->num == NULL) {
printf("Error!");
return 0;
}
strcpy(ptr->name,(char*)malloc(sizeof(char) * 40));
if (ptr == NULL) {
printf("Error!");
return 0;
}
ptr->age = (int*)malloc(sizeof(int));
if (ptr->age == NULL) {
printf("Error!");
return 0;
}
ptr->goals = (int*)malloc(sizeof(int));
if (ptr->goals == NULL) {
printf("Error!");
return 0;
}
ptr->Amatch = (int*)malloc(sizeof(int));
if (ptr->Amatch == NULL) {
printf("Error!");
return 0;
}
if (j == player_num - 1) {
ptr->next = NULL;
}
ptr = ptr->next;
}
这就是我获取malloc的方式。我也很好奇,有一种更简单的方法来获取malloc。
while (ptrW != NULL) {
printf("**Player%d**\n",i);
printf("Number : ");
scanf("%d",ptrW->num);
printf("Name : ");
scanf(" ");
gets_s(ptrW->name,sizeof(ptrW->name));
printf("Age: ");
scanf("%d",ptrW->age);
printf("A-matches : ");
scanf("%d",ptrW->Amatch);
printf("goals : ");
scanf("%d",ptrW->goals);
printf("\n");
i++;
ptrW = ptrW->next;
}
这是问题所在。输入player1的成员时,它执行良好,但是在输入player2的num之前,该程序已关闭。