我正在尝试返回一组 char
数组。虽然我能够成功创建数组,但我显然错误地返回了它。
是我的语法错误还是我犯了一些我忽略的其他错误?
这里是最相关的行,后面是完整的函数
// prototype
char * testFunc();
// Function
char * testFunc() {
char* ptrArray[2];
return(*ptrArray);
}
// Assignment in main()
int main {
char * res = testFunc();
}
这里是完整代码的简化版本
#include <iostream>
using std::cout;
// prototype
char * testFunc();
int main() {
short i, j;
char * res = testFunc();
for (i=0; i < 2; i++)
cout <<"This is res[" << i << "] : " << res[i] <<"\n";
return(0);
}
char * testFunc() {
char word1[] = "one";
char word2[] = "two";
// create an array of char*
char* ptrArray[2];
ptrArray[0] = word1;
ptrArray[1] = word2;
for (int i=0; i<2; i++)
cout <<"This is ptrArray[" << i << "] : " << ptrArray[i] <<"\n";
return(*ptrArray);
}
最佳答案
从函数返回分配在自动存储中的对象(也称为“堆栈对象”)是未定义的行为。当您需要在 C 中返回一个数组时,您有以下三种选择:
- 返回一个分配在静态存储区的对象,
- 返回一个在动态存储区分配的对象,或者
- 获取缓冲区和最大大小,并返回数组的实际大小。
第一个选项很少适用,因为它使您的函数不可重入。第三种选择很普遍,但它有局限性:当您必须返回比缓冲区容纳的数据更多的数据时,需要多次调用 API。
这给我们留下了第二个选项:使用 new
分配您要返回的内存,将数据复制到其中,并将结果返回给调用者。现在调用者有责任释放动态内存:
// You need two asterisks: a string needs one asterisk, you return
// a 1-D array of strings, so you need another level of indirection.
char ** testFunc() {
char word1[] = "one"; // Automatic memory - needs a copy
char word2[] = "two"; // Automatic memory - needs a copy
// create an array of char*
char** ptrArray = new char*[2];
ptrArray[0] = new char[strlen(word1)+1]; // Plus one for the null terminator
strcpy(ptrArray[0], word1);
ptrArray[1] = new char[strlen(word2)+1]; // Plus one for the null terminator
strcpy(ptrArray[1], word2);
for (int i=0; i<2; i++)
cout <<"This is ptrArray[" << i << "] : " << ptrArray[i] <<"\n";
return ptrArray;
}
注意:您可能还没有达到标准库,因此下面的解决方案可能不适用。但是,您应该知道上面的解决方案不是 C++ 可以做的最好的解决方案:您可以用动态容器重写这个,并使代码更易于阅读:
vector<strig> testFunc() {
vector<string> res;
res.push_back("one");
res.push_back("two");
return res;
}
在 C++11 中你可以做得更好:
vector<string> test() {
return vector<string> {"one", "two"};
}
关于c++ - 从函数返回 char 指针数组 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17757617/