如何从递归函数返回字符串数组?

vj0*_*j01 0 c arrays string

如何从递归函数返回字符串数组?

例如::

char ** jumble( char *jumbStr)//reccurring function
{
   char *finalJumble[100];

   ...code goes here...call jumble again..code goes here

   return finalJumble;
} 
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Did*_*set 6

在C中,您无法从函数返回字符串.您只能返回指向字符串的指针.因此,您必须将要返回的字符串作为参数传递给函数(不要使用全局变量或函数本地静态变量),如下所示:

char *func(char *string, size_t stringSize) {
    /* Fill the string as wanted */
    return string;
}
Run Code Online (Sandbox Code Playgroud)

如果要返回一个字符串数组,这更复杂,尤其是如果数组的大小不同.最好的恕我直言可能是返回相同字符串中的所有字符串,连接字符串缓冲区中的字符串,并将空字符串作为最后一个字符串的标记.

char *string = "foo\0bar\0foobar\0";
Run Code Online (Sandbox Code Playgroud)

您当前的实现不正确,因为它返回指向本地函数范围中定义的变量的指针.

(如果你真的使用C++,那么返回一个std::vector<std::string>.)

  • @che:编译器已经添加了最后一个'\ 0'.无需添加它! (3认同)