在C++中返回C字符串数组

Dae*_*erl 0 c++ arrays cstring

我的功能有这个原型:

char[][100] toArray(char document[]);
Run Code Online (Sandbox Code Playgroud)

g ++ on cygwin返回此错误:

Unable to resolve identifier toArray
Run Code Online (Sandbox Code Playgroud)

如何返回C-Strings数组?

joh*_*ohn 6

用C++返回一个数组是不可能的.您可以做的最接近的是返回一个指向动态分配的字符串块的指针.

这是合法代码

typedef char str100[100];

str100* toArray(char* document)
{
    str100 *block = new str100[20];
    return block;
}
Run Code Online (Sandbox Code Playgroud)

typedef让它更容易理解.如果你不相信我这里没有typedef的相同代码

char (*toArray(char* document))[100]
{
    char (*block)[100] = new char[20][100];
    return block;
}
Run Code Online (Sandbox Code Playgroud)

这是为了吓唬你.

但是,虽然这段代码是合法的,但它也是垃圾.你应该使用std::vector<std::string>.动态分配内存很难,比使用为您工作的类要困难得多.