簡體   English   中英

在函數之間傳遞指向struct數組的指針

[英]Passing pointer to struct array between functions

我有一個程序,需要將一些文本逐字加載到一個數組中,所以我有一個結構用於定義的每個文本

main.h

typedef struct wordTag{
 char name[MAX_WORD];
 char string[1000][MAX_WORD];
 int words;
}text;

main.c中

void main(){
   int fileCount = 0;
   text *checkTexts;
   fileCount = getCheckFiles(checkTexts);

   for(i = 0; i < fileCount; i++){
    printf("Tekst navn: %s\n", checkTexts[i].name);
   }
}

file.c

int getCheckFiles(text *checkTexts){

int fileCount, i;

FILE *file;

createFileList(&file);
fileCount = countFiles(file);

createArray(checkTexts, fileCount, file);

return fileCount;



}

void createArray(text *checkTexts, int fileCount, FILE *file){
 int i, wordCount;
 FILE *textFile;
 text localText;
 char fileName[MAX_WORD + 30];


 checkTexts= (text *)malloc(fileCount * sizeof(text));

 readFileNames(file, checkTexts);

 for(i = 0; i < fileCount; i++){
  localText = checkTexts[i];
  strcpy(fileName, "./testFolder/");
  strcat(fileName, localText.name);
  openFile(&textFile, fileName);

  localText.words = countWords(textFile);

  readFileContent(textFile, localText);
  checkTexts[i] = localText;
 }

  for(i = 0; i < fileCount; i++){
  printf("Tekst navn: %s\n", checkTexts[i].name);

  }

}

現在,如果我在createArray函數中打印名稱,每件事都可以正常工作,但如果我嘗試在主函數中打印,我會遇到分段錯誤(核心轉儲)。

您尚未初始化在main()中使用的checkTexts指針。

在C(或C ++)中,函數指針通過而不是通過引用傳遞(在C ++中,當聲明函數將類型引用作為參數時)。 所以當你調用getCheckFiles(checkTexts)getCheckFiles(checkTexts) getCheckFiles()對傳入參數的作用並不main() - 它不會改變main()checkTexts變量。

然后在你對createArray()調用中發生同樣的事情。 因此,盡管您在createArray()創建了數組,但是您指向malloc的緩沖區的指針永遠不會傳播回調用鏈。

問題是createArray中的malloc調用不會將內存塊與您提供的地址( checktextschecktexts就像您可能默認的那樣,而是提供一個指向它已保留的內存塊的指針。 您提供的checkTexts (內存地址)的值將在createArray被覆蓋; checkTexts也可能是一個局部變量。 然而,當createArray返回時,它仍然是checkTextsmain引用的舊的 ,未初始化的地址,並且該地址處的內存(可能)就像以前一樣,即未分配或為其他人保留。 所以,分段錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM