我想用这个程序将哈希表写入文件 但我明白了
cannot convert parameter 1 from 'fpinfo' to 'const void *'
编译时出错
如果我将 struct fpinfo e;
更改为 struct fpinfo *e
我会收到运行时错误:
The variable 'e' is being used without being initialized.
我试图通过将 e 声明为 struct fpinfo *e=NULL;
来初始化它。这要么不起作用。
请像往常一样给我你的帮助。
WriteHTtoFile(struct fpinfo t[][B_ENTRIES],int this_tanker,tanker_record tr[][BUCKETS])
{
//struct fpinfo *e;
struct fpinfo e;
int i=0, mask;
char filename[sizeof ("file0000.txt")];
sprintf(filename, "filee%d.txt", this_tanker);
curr_tanker++;
//fp = fopen(filename,"w");
FILE *htfile=fopen(filename,"w+b");
system("cls");
if (htfile != NULL)
{
for (int j = 0; j < BUCKETS; ++j)
{
for (int k = 0; k < tr[this_tanker][j].bkt.num_of_entries; ++k)
{
printf("%d\t%d\t%s\n",t[j][k].chunk_offset,t[j][k].chunk_length,t[j][k].fing_print);
(e).chunk_offset=t[j][k].chunk_offset;
(e).chunk_length=t[j][k].chunk_length;
strcpy((char*)((e).fing_print),(char*)t[j][k].fing_print);
fwrite(e,sizeof(fpinfo),1,htfile);
}
}
fclose(htfile);
}
else
{
std::cout<<"File could not be opend for writing";
printf("Error %d\t\n%s", errno,strerror(errno));
}
fclose(htfile);
return 1;
}
最佳答案
fwrite()
的第一个参数是 const void*
。这传递了一个 struct fpinfo
:
fwrite(e, sizeof(fpinfo), 1, htfile);
更改为:
fwrite(&e, sizeof(fpinfo), 1, htfile);
我不确定 struct fpinfo
的成员是什么,所以这可能是不安全的(例如,如果它包含任何指针成员)。 struct fpinfo
中成员的任何 future 重新排序或导致 struct fpinfo
大小增加的更改(如添加新成员)意味着任何尝试读取以前写入的 struct fpinfo
数据将不正确。
当 e
的声明更改为 struct fpinfo* e;
时,单元化错误是由于指针不是 NULL 或被分配给动态分配的 struct fpinfo
.
当更改为 struct fpinfo *e = NULL;
时,当试图访问 e
的任何成员时,这将导致段错误,因为它没有指向struct fpinfo
.
关于c++ - 为什么我得到变量 -- is being used without being initialized 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9485389/