如何从函数返回一个字符串数组

fri*_*nds 10 c

char * myFunction () {

    char sub_str[10][20]; 
    return sub_str;

} 

void main () {

    char *str;
    str = myFunction();

}
Run Code Online (Sandbox Code Playgroud)

错误:从不兼容的指针类型返回

谢谢

Die*_*lla 17

C中的字符串数组可以与char**或一起使用char*[].但是,您无法返回存储在堆栈中的值,就像在函数中一样.如果要返回字符串数组,则必须动态保留它:

char ** sub_str = malloc(10 * sizeof(char*));
for (int i =0 ; i < 10; ++i)
    sub_str[i] = malloc(20 * sizeof(char));
/* Fill the sub_str strings */
return sub_str;
Run Code Online (Sandbox Code Playgroud)

然后,main可以像这样得到字符串数组:

char** str = myFunction();
printf("%s", str[0]); /* Prints the first string. */
Run Code Online (Sandbox Code Playgroud)


Tho*_*s E 7

对于刚开始的程序员来说,"堆栈"或"堆"的概念可能有点令人困惑,特别是如果你已经开始使用Ruby,Java,Python等更高级别的语言编程.

考虑:

char **get_me_some_strings() {
  char *ary[] = {"ABC", "BCD", NULL};
  return ary;
}
Run Code Online (Sandbox Code Playgroud)

编译器将正确地发出关于尝试返回局部变量的地址的投诉,并且您肯定会在尝试使用返回的指针时遇到分段错误.

和:

char **get_me_some_strings() {
  char *ary[] = {"ABC", "BCD", NULL};
  char **strings = ary;
  return strings;
}
Run Code Online (Sandbox Code Playgroud)

将关闭编译器,同时仍然得到相同的讨厌的分段错误.

为了让除了狂热者之外的所有人都感到高兴,你会做一些更精细的事情:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **get_me_some_strings() {
  char *ary[] = { "ABC", "BCD", NULL };
  char **strings = ary; // a pointer to a pointer, for easy iteration
  char **to_be_returned = malloc(sizeof(char*) * 3);
  int i = 0;
  while(*strings) {
    to_be_returned[i] = malloc( sizeof(char) * strlen( *strings ) );
    strcpy( to_be_returned[i++], *strings);
    strings++;
  }
  return to_be_returned;
}
Run Code Online (Sandbox Code Playgroud)

现在使用它:

void i_need_me_some_strings() {
  char **strings = get_me_some_strings();
  while(*strings) {
    printf("a fine string that says: %s", *strings);
    strings++;
  }
}
Run Code Online (Sandbox Code Playgroud)

只要记住在完成后释放分配的内存,因为没有人会为你做.这适用于所有指针,而不仅仅是指向指针的指针!(我认为).

为了更好地理解这一切,您可能还想阅读:堆栈和堆的内容和位置是什么?