how to return a string array from a function

后端 未结 9 715
暖寄归人
暖寄归人 2020-12-29 10:53
char * myFunction () {

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

} 

void main () {

    char *str;
    str = myFunction();

}

error:return

9条回答
  •  长情又很酷
    2020-12-29 11:09

    A string array in C can be used either with char** or with char*[]. However, you cannot return values stored on the stack, as in your function. If you want to return the string array, you have to reserve it dynamically:

    char** myFunction() {
        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;
    }
    

    Then, main can get the string array like this:

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

    EDIT: Since we allocated sub_str, we now return a memory address that can be accessed in the main

提交回复
热议问题