Хотя я изменил 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, но перед вводом num player2 программа закрывается.