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:
char **array = malloc(20 * sizeof(char *));
int i;
for(i=0; i != 20; ++i) {
array[i] = malloc(20 * sizeof(char));
}
Then returning array works
You should just return array
( return array;
). the **
after declaration are used for dereferencing.
Also, make sure the the memory for this array is allocated on the heap (using malloc
or simillar function)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.