gpt4 book ai didi

c - 在 C 中返回多维字符数组

转载 作者:太空宇宙 更新时间:2023-11-04 05:45:10 25 4
gpt4 key购买 nike

在 C 中,如何创建返回字符串数组的函数?还是多维字符数组?

例如,我想返回一个在函数中创建的数组 char paths[20][20]

我最近的尝试是

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

}

我尝试了各种“设置”,但每一个都会出现某种错误。

我不知道 C 是怎么工作的

最佳答案

您不能安全地返回堆栈分配的数组(使用数组[20][20] 语法)。

你应该使用 malloc 创建一个动态数组:

char **array = malloc(20 * sizeof(char *));
int i;
for(i=0; i != 20; ++i) {
array[i] = malloc(20 * sizeof(char));
}

然后返回数组就可以了

关于c - 在 C 中返回多维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7622199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com