tam*_*am5 4 c arrays string heap-memory stack-memory
我试图调用一个方法,该方法将生成一个2D char数组(字符串数组)并将其返回以在另一个函数中使用。
我的例子:
char ** example(void)
{
char *test[3];
int i;
for (i = 0; i < 3; i++) {
test[i] = malloc(3 * sizeof(char));
}
test[foo][bar] = 'baz'; // of course I would declare 'foo' and 'bar'
// ...
// ...
return test;
}
Run Code Online (Sandbox Code Playgroud)
然后,我希望能够如下使用数组:
void otherMethod(void)
{
char ** args = example();
// do stuff with args
}
Run Code Online (Sandbox Code Playgroud)
问题是这会产生错误:
警告:与局部变量“ test”关联的堆栈内存地址已返回[-Wreturn-stack-address]
我可以通过test在全局范围(而不是局部范围)中进行定义来解决此问题,但是我宁愿不要这样做,因为它看起来很杂乱,尤其是如果我要拥有其中几个。
有没有一种方法可以在C中创建和返回字符串数组,而无需全局定义它?
您走在正确的轨道上。您需要做的就是将test[3];自身的分配从自动(也称为“堆”)更改为动态(即“堆”):
char **test = malloc(3 * sizeof(char*));
Run Code Online (Sandbox Code Playgroud)
这使得test从函数中返回是合法的,因为它将不再返回与堆栈分配关联的地址。
当然,要求调用者free同时使用返回内部的指针和返回本身。您可能要考虑为此提供一个辅助函数。
另一种方法是将char test[]参数用作函数参数:
void example(char *test[], size_t count) {
for (size_t i = 0 ; i < count ; i++) {
test[i] = malloc(3 * sizeof(char));
}
...
// return is not required
}
Run Code Online (Sandbox Code Playgroud)
现在,调用者将必须将适当大小的数组传递给函数,以便避免分配它。