How do I return a char array from a function?

后端 未结 6 1119
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 13:13

I\'ve tried the following:

char[10] testfunc()
{
    char[10] str;

    return str;
}
6条回答
  •  一向
    一向 (楼主)
    2020-11-28 14:06

    a char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappear when the function exits. Use something like this:

    char *testfunc() {
        char* arr = malloc(100);
        strcpy(arr,"xxxx");
        return arr;
    }
    

    This of course if you are returning an array in the C sense, not an std:: or boost:: or something else. As noted in the comment section: remember to free the memory from the caller.

提交回复
热议问题