Returning a string from a function in C

前端 未结 7 1074
耶瑟儿~
耶瑟儿~ 2020-12-18 07:28

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

相关标签:
7条回答
  • 2020-12-18 08:01

    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

    0 讨论(0)
提交回复
热议问题