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
checkTextspointer which you are using inmain().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 whatgetCheckFiles()does with the passed-in parameter — it doesn’t changemain()‘scheckTextsvariable.The same thing then happens down in your call to
createArray(). So although you create the array down increateArray(), the pointer to the buffer you malloc’d never propagates back up the call chain.