I have a c function that I want to return a string.
If I print the string before it is returned then I see croc_data_0186.idx
If I try and print the string
There are 3 ways you can solve this
1) Make 'fileNameString' static
static char fileNameString[100];
2) Caller of the function 'getSegmentFileName' should pass a character buffer 'segmentFileName' to the callee i.e.
getSegmentFileName(file, lineLength, mid, segmentFileName);
In this case you need to change the function arguments
char* getSegmentFileName(FILE *file, int lineLength, int lineNumber, char *segmentFileName) {
.....
strcpy(segmentFileName, fileNameString); // copying the local variable 'fileNameString' to the function argument
// so that it wont be lost when the function is exited.
return fileNameString; // there is no need to return anything and you can make this function void
// in order not to alter ur program I am putting the return also
}
3) In this way you can dynamically allocate the memory for the fileNameString. Dynamic memory is allocated in the heap and it wont be lost when the function returns. So you can safely use it in the indexSearch function.
char* getSegmentFileName(FILE *file, int lineLength, int lineNumber)
{
char *fileNameString = (char *)malloc(100 * sizeof(char)); // allocate memory for 100 character string
.....
return fileNameString;
}
In this case you will need to free the memory pointed by fileNameString using free