我正在尝试在我的代码中应用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)
希望你能帮助我...在此先感谢:)