Returning a string from a function in C

前端 未结 7 1090
耶瑟儿~
耶瑟儿~ 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 07:44

    You are returning a pointer to local data, which is not valid after the function returns. You have to allocate the string properly.

    This can be done in either the calling function, by supplying a buffer to the called function, and it copies the string over to the supplied buffer. Like this:

    char segmentFileName[SOME_SIZE];
    getSegmentFileName(file, lineLength, mid, segmentFileName);
    

    and the getSegmentFileName function:

    void getSegmentFileName(FILE *file, int lineLength, int lineNumber, char *segmentFileName)
    {
        /* ... */
    
        strcpy(segmentFileName, fileNameString);
    }
    

    The other solution is to allocate the memory for the string in getSegmentFileName:

    return strdup(fileNameString);
    

    but then you have to remember to free the string later.

提交回复
热议问题