写入文件时出现 malloc 问题
每当我将数据写入文本文件时,就会出现垃圾数据...为什么会这样? 这是我的代码...谢谢
int main(void)
{
unsigned int option = 0;
int i = 0;
}
getch();
while(option != 5){
option = display();
switch(option){
case 5: save();
break;
}
for(i = 0; i < recordCtr; i++){
free(array[i]);}
}
}
save(){
FILE *stream = NULL;
stream = fopen("student.txt", "wt");
printf("\nSaving the student list directory. Wait a moment please...");
int i =0;
for (i=0; i<3; i++){
fprintf(stream, "%5s %30s %5s\n", array[i]->studentID, array[i]->name, array[i]->course);
}
fclose(stream);
}
A garbage data appears whenever i write the data in the text file... Why is it like that?
Here's my code... Thanks
int main(void)
{
unsigned int option = 0;
int i = 0;
}
getch();
while(option != 5){
option = display();
switch(option){
case 5: save();
break;
}
for(i = 0; i < recordCtr; i++){
free(array[i]);}
}
}
save(){
FILE *stream = NULL;
stream = fopen("student.txt", "wt");
printf("\nSaving the student list directory. Wait a moment please...");
int i =0;
for (i=0; i<3; i++){
fprintf(stream, "%5s %30s %5s\n", array[i]->studentID, array[i]->name, array[i]->course);
}
fclose(stream);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一些错误。
什么时候看到垃圾数据。我的意思是在什么输入下?
There are some bugs.
When do you see garbage data. I mean under what Input?
您从未为 struct Student *array[MAX]; 分配内存;我认为这可能会覆盖您的数据?
strcpy(array[0]->studentID, dummy);
studentID 是 char[5],dummy 是 char[30]。自从使用 C for m 以来已经有一段时间了,但您可能会破坏其他数据。
You never allocate memory forstruct student *array[MAX];
I think this is overwriting your data maybe?
strcpy(array[0]->studentID, dummy);
studentID is a char[5] and dummy is a char[30]. It's been a while since using C for m, but you could be smashing your other data.