I'm new to c programming and wanted to write a helper function for myself that should do the following
- Receiving a char** as first input parameter
- Receiving const char* as second input parameter (path to file)
- Reading in the file and populating char** with the read in lines
- Returning the number of lines read in so that the calling function "knows" the size of the passed in array
The idea is to have a helper function that will do the job of reading in a file without needing to rewrite the logic all the time again.
I continuously received segmentation faults and therefore reduced this for debugging to the following test case (still not working):
Test function:
int test_read_in_file() {
char **arrayLinesOfFile;
int numberOfRowsReadIn = read_in_file("test_file.txt",
arrayLinesOfFile);
printf("%s\n", arrayLinesOfFile[0]); // gives segmentation fault
}
The function (reduced to a simple test for now):
int read_in_file(const char* pathToFile, char** linesOfFile) {
int numberOfRows = 5;
linesOfFile = (char**) malloc(numberOfRows * sizeof(char*));
linesOfFile[0] = malloc(10 * sizeof(char)); // just for testing
strcpy(linesOfFile[0], "Andreas"); // just for testing
printf("%s\n",linesOfFile[0]); // this works fine, output "Andreas"
return numberOfRows;
}
When running this test case, the printf statement in the function works fine, the printf in the test runner gives a segmentation fault.
I don't understand why this is happening. In my understanding linesOfFile would be passed by references, then I allocate memory for the first element and then sufficient elements to hold "Andreas" in the first element.
Any help would be highly appreciated.
Thanks Andreas