So imagine this fairly simple scenario. I have some function that does some manipulations and ends up returning an array of char pointers. For the sake of simplicity, let that function take no arguments:
#include <stdio.h>
char **func(void);
int main() {
printf("%s\n", func()[0]);
return 0;
}
char **func() {
static char arr[3][10] = {"hi", "bye", "cry"};
return arr;
}
I want to be able to access this array in my main() function. I make the array static in order to avoid returning the address to a local variable defined in the scope of func(). This code compiles, but with a warning:
warning: return from incompatible pointer type [-Wincompatible-pointer-types]
return arr;
^
But what should I make the return argument then? A pointer to a char array? I thought that in C returning an array is bad practice.
Running this program results in an unhelpful segmentation fault.
So what am I doing incorrectly? Can I not return a pointer to an array of char pointers? Hence, a char **? Am I conflating array/pointer decay? How would I return an array of strings? Is there a way to return a string array without the use of the static keyword?
Edit: Surely you all are able to empathize with my confusion? It's not like the array-pointer decay functionality of C is trivial to reason about.
char *.char**andchar[][]is not the same data type. Why not declare your array asstatic char *arr[] = {"hi", "bye", "cry"};Then you can returnarras in the original code.