2012-02-28 35 views
0

我想利用這個程序來哈希表寫入文件 ,但我得到爲什麼我變量 - 正在使用而沒有被初始化錯誤?

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; 
} 
+0

這是C++,而不是固定標籤。 – 2012-02-28 16:09:51

+0

該文件應該在什麼格式?看起來你只是錯過了將'e'轉換爲文件應該處於的任何格式的代碼。你不能只將內存內容寫入文件,並期望它稍後有意義,除非已經序列化這些內容採用已知的格式。 – 2012-02-28 16:16:19

+0

@DavidSchwartz它是一個二進制文件,我已經成功地將它寫入並讀取,謝謝你們全部 – John 2012-02-28 16:28:42

回答

3

fwrite()的第一個參數是const void*。這傳遞一個struct fpinfo

fwrite(e, sizeof(fpinfo), 1, htfile); 

更改爲:

fwrite(&e, sizeof(fpinfo), 1, htfile); 

我不確定什麼struct fpinfo的成員所以這可能是不安全的(如果,例如,它包含的任何指針成員)。任何未來對struct fpinfo中的成員重新排序或導致大小增加struct fpinfo(如添加新成員)的更改意味着任何嘗試讀取以前編寫的struct fpinfo數據都將不正確。

e的聲明更改爲struct fpinfo* e;時,單位化錯誤是由於指針不爲NULL或分配給動態分配的struct fpinfo所致。

當更改爲struct fpinfo *e = NULL;時,如果嘗試訪問e的任何成員時發生分段錯誤,因爲它未指向struct fpinfo

相關問題