简体   繁体   中英

Passing pointer to struct array between functions

I have a program which needs to load some text word for word into an array, so i have a struct for each text defined in

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);

  }

}

Now if I print the name in the createArray function every thing works fine, but if i try and print in my main function I get a segmentation fault (core dumped).

You have not initialised the checkTexts pointer which you are using in main() .

In C (or C++) function pointers are passed by value not by reference (with the exception, in C++, of when a function is declared to take a reference to a type as a parameter). So when you call getCheckFiles(checkTexts) it doesn't matter what getCheckFiles() does with the passed-in parameter -- it doesn't change main() 's checkTexts variable.

The same thing then happens down in your call to createArray() . So although you create the array down in createArray() , the pointer to the buffer you malloc'd never propagates back up the call chain.

The problem is that the malloc call within createArray doesn't associate a block of memory with the address you've supplied ( checktexts ) as you may be tacitly assuming, rather it provides a new pointer to a block of memory it has reserved. The value of checkTexts (the memory address) you've supplied is overwritten within createArray ; checkTexts might as well be a local variable. When createArray returns however, it's still the old , uninitialized address that checkTexts refers to within main , and the memory at that address is (probably) just as it was before, namely either unallocated or reserved for someone else. So, segmentation fault

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM