malloc的问题

iam*_*ice 1 c malloc

我正在尝试在我的代码中应用malloc,但仍然有问题,有一个错误说:"请求成员'id'在非结构或联合的东西中".

我想要做的是使用malloc而不是数组..并将结构存储在每个索引中,我尝试了array [i] - > id,但是我的文本文件中存储了一堆垃圾字符.我也增加了我并没有使用循环,因为用户可能只输入一次...这是我的代码:

#include<stdio.h>
#include<stdlib.h>
struct studentinfo{
       char id[8];
       char name[30];
       char course[5];
}s1;
main(){
    int i=0;
    FILE *stream = NULL;
    stream = fopen("studentinfo.txt", "a+");    
    struct studentinfo *array[50];

    array[i] = (struct studentinfo*) malloc(sizeof(struct studentinfo));
       printf("Enter Student ID: ");
       scanf("%s", array[i].id);
       fflush(stdin);
       printf("Enter Student Name: ");
       gets(array[i].name);
       fflush(stdin);
       printf("Enter Student Course: ");
       scanf("%s", array[i].course);

       fprintf(stream, "\n%s,\t%s,\t%s", array[i].id, array[i].name, array[i].course);
       i++;
       fclose(stream);
       free(array);
    getch();
}
Run Code Online (Sandbox Code Playgroud)

希望你能帮助我...在此先感谢:)

Der*_*k H 5

您正在错误地访问这些属性.

array[i]

是指向结构的指针,所以

array[i].id

会给你一个错误.使用

array[i]->id

解除引用.