In C, how can I create a function which returns a string array? Or a multidimensional char array?
For example, I want to return an array char paths[20][20] created in a function.
My latest try is
char **GetEnv()
{
int fd;
char buf[1];
char *paths[30];
fd = open("filename" , O_RDONLY);
int n=0;
int c=0;
int f=0;
char tmp[64];
while((ret = read(fd,buf,1))>0)
{
if(f==1)
{
while(buf[0]!=':')
{
tmp[c]=buf[0];
c++;
}
strcpy(paths[n],tmp);
n++;
c=0;
}
if(buf[0] == '=')
f=1;
}
close(fd);
return **paths; //warning: return makes pointer from integer without a cast
//return (char**)paths; warning: function returns address of local variable
}
I tried various ‘settings’ but each gives some kind of error.
I don’t know how C works
You can’t safely return a stack-allocated array (using the array[20][20] syntax).
You should create a dynamic array using malloc:
Then returning array works