【发布时间】:2015-03-27 02:35:47
【问题描述】:
我正在用 C 语言完成我的大学项目,但遇到了一些问题。 我使用了指向结构的指针,并使用 fwrite 将其写入文件,但它没有帮助。这是我使用的代码。
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
struct collection{
char *fname, *lname, *telephone, *address, *seat;
};
collection * alloc( ){
struct collection *r = (struct collection *) malloc (sizeof(collection*));
r->fname = NULL;
r->lname = NULL;
r->telephone = NULL;
r->address = NULL;
r->seat = NULL;
return (r);
}
void string_realloc_and_copy (char **dest, const char *src){
*dest =(char *) realloc (*dest, strlen (src) + 1);
strcpy (*dest, src);
}
int main(){
char ch = 'Y', temp[50];
FILE *ptf;
struct collection *asd;
asd = alloc();
//printf("%d",sizeof(asd));
//opening file
ptf = fopen("lang.txt","w+");
do{
printf("First name: ");
gets(temp);
string_realloc_and_copy(&asd->fname,temp);
printf("Last name: ");
gets(temp);
string_realloc_and_copy(&asd->lname,temp);
printf("Telephone: ");
gets(temp);
string_realloc_and_copy(&asd->telephone,temp);
printf("Address: ");
gets(temp);
string_realloc_and_copy(&asd->address,temp);
printf("Seat you want to book: ");
gets(temp);
string_realloc_and_copy(&asd->seat,temp);
fwrite(asd,12*sizeof(collection),1,ptf);
fflush(ptf);
//fprintf(ptf,"\n");
printf("Do you wish to enter another data...? (Y/N) ");
ch = getch();
}while((ch=toupper(ch))== 'Y');
rewind(ptf);
while(fread(asd,12*sizeof(collection),1,ptf) == 1){
printf("\n\n%s",asd->fname);
printf("\n\n%s",asd->lname);
printf("\n\n%s",asd->telephone);
printf("\n\n%s",asd->address);
printf("\n\n%s",asd->seat);
}
fclose(ptf);
}
它一直工作到 asd->telephone 到达它要求地址并且没有响应。我无法弄清楚我做错了什么。我以为是内存不足所以我改变了
struct collection *r = (struct collection *) malloc (sizeof(collection*));
到 struct collection *r = (struct collection *) malloc (12*sizeof(collection*));
它工作了一段时间,同样的事情一次又一次地发生了。我正在使用 devC++ 进行编译。提前致谢;
【问题讨论】:
-
顺便说一句,您可以使用 calloc(1, sizeof(collection)) 并避免将所有结构元素设置为 NULL。
-
您对 realloc() 的使用也是错误的。第一个参数必须是指向您要重新分配和调整大小的东西的指针。在您的情况下,它总是作为 NULL 传入,因为您从未为 fname、lname 等分配任何内存。为什么不直接使用 strdup() 而不是 realloc/strcpy?
-
你确定这是 C 而不是 C++?
标签: c pointers struct file-handling