返回C语言的多维字符数组



在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是怎么工作的

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

你应该使用malloc: 创建一个动态数组
char **array = malloc(20 * sizeof(char *));
int i;
for(i=0; i != 20; ++i) {
    array[i] = malloc(20 * sizeof(char));
}

然后返回数组

您应该只返回array (return array;)。声明后的**用于解引用。

另外,确保这个数组的内存是在堆上分配的(使用malloc或类似的函数)

最新更新