[英]Return multidimensional char array in C
In C, how can I create a function which returns a string array? 在C语言中,如何创建一个返回字符串数组的函数? Or a multidimensional char array? 还是多维char数组?
For example, I want to return an array char paths[20][20]
created in a function. 例如,我想返回在函数中创建的数组char paths[20][20]
。
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 我不知道C是如何工作的
You can't safely return a stack-allocated array (using the array[20][20] syntax). 您不能安全地返回使用堆栈分配的数组(使用array [20] [20]语法)。
You should create a dynamic array using malloc: 您应该使用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;
). 您应该只返回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) 另外,请确保此数组的内存在堆上分配(使用malloc
或simillar函数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.