I am trying to call a method that will generate a 2D char array (array of strings) and return it to be used in another function.
My example:
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;
}
And then I would like to be able to use the array as follows:
void otherMethod(void)
{
char ** args = example();
// do stuff with args
}
The problem is that this produces the error:
warning: address of stack memory associated with local variable 'test' returned [-Wreturn-stack-address]
I could solve this problem by defining test
in the global scope as opposed to locally, but I would very much rather not do this as it seems messy, especially if I am to have several of these.
Is there a way to create and return an array of strings in C without defining it globally?