我想在我的代码中应用malloc,但仍然有问题,有一个错误说:“请求成员'id在某些不是结构或联盟”。在malloc问题
我想要做的就是使用malloc而不是数组.. ..并将结构存储在每个索引中,我试过数组[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();
}
希望你能帮助我...在此先感谢:)
`fflush(stdin)`调用未定义的行为。 – 2010-12-04 04:10:14
并更改gets()函数,因为QUOTE“它是创建缓冲区溢出的恶魔工具”... http://stackoverflow.com/questions/4346598/gets-function-in-c – newbie 2010-12-04 04:23:23
你想做一个StudentInfo数组,还是您想要创建一个指向StudentInfo的指针数组?因为你做了后者,而且看起来你想要前者。 – 2010-12-04 04:08:09