在链表中,输入结构的成员时程序会关​​闭

尽管我将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之前,该程序已关闭。

weiwei398 回答:在链表中,输入结构的成员时程序会关​​闭

在这种情况下,您只需要为结构本身分配空间,而无需为成员变量分配空间。

ptr = (struct player*)malloc(sizeof(struct player));
if (ptr == NULL) {
    printf("Error!");
    return 0;
}

您还应该在对scanf的调用中指定变量的地址。

    scanf("%d",&ptrW->num);
    scanf("%d",&ptrW->age);
    scanf("%d",&ptrW->Amatch);
    scanf("%d",&ptrW->goals);
,

首先: 我认为您应该在j!= 0时使用realloc。 您不会丢失字符串数据。 其次:malloc / realloc / calloc是我们用来分配内存块的函数,您只能在指针上使用它们(分配之后,指针将指向该块的第一种情况) 第三:函数strcpy()需要从字符串中复制-当您将malloc使用到strcpy()中时->编译器不知道要复制什么(分配块中没有值)。 希望对您有帮助

本文链接:https://www.f2er.com/3155027.html

大家都在问