Work around error 'Address of stack memory associated with local variable returned'
You are on the right track. All you need to do is to change the allocation of the test[3];
itself from automatic (aka "stack") to dynamic (aka "heap"):
char **test = malloc(3 * sizeof(char*));
This makes it legal to return test
from your function, because it would no longer be returning an address associated with stack allocation.
Of course the caller would be required to free
both the pointers inside the return, and the return itself. You may want to consider supplying a helper function for that.
Another approach would be to take char test[]
as a function parameter:
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
}
Now the caller would have to pass an array of suitable size into your function, so that you could avoid allocating it.