Returning a string from a function in C

前端 未结 7 1094
耶瑟儿~
耶瑟儿~ 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条回答
  •  Happy的楠姐
    2020-12-18 07:43

    It is because you return invalid pointers.

        char* fileNameString;
    

    is just a pointer.

        char line[lineLength];
    

    lives on the stack and is filled with a fgets() call.

        char *lineElements[3];
        lineElements[0] = strtok(line, ":");
        lineElements[1] = strtok(NULL, ":");
        lineElements[2] = strtok(NULL, ":");
    

    Here you store pointers into that array. One of them is

        fileNameString = lineElements[2];
    

    which you

        return fileNameString;
    

    afterwards.

    The solution would be to

    • either malloc enough space inside the function and copy your string to the new memory block or

    • have the caller provide a buffer you write the data into.

提交回复
热议问题