Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return a string array from a function

Tags:

c

char * myFunction () {

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

} 

void main () {

    char *str;
    str = myFunction();

}

error:return from incompatible pointer type

thanks

like image 599
friends Avatar asked Nov 03 '10 08:11

friends


People also ask

Can we return an array from function?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

How do you return a string array in Python?

To return the length of a string array element-wise, use the numpy. char. str_len() method in Python Numpy. The method returns an output array of integers.


2 Answers

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

like image 133
Diego Sevilla Avatar answered Sep 19 '22 02:09

Diego Sevilla


As others have said, you cannot return a local char array to the caller, and have to use heap memory for this.

However, I would not advise using malloc() within the function.

Good practice is that, whoever allocates memory, also deallocates it (and handles the error condition if malloc() returns NULL).

Since your myFunction() does not have control over the memory it allocated once it returned, have the caller provide the memory in which to store the result, and pass a pointer to that memory.

That way, the caller of your function can de-allocate or re-use the memory (e.g. for subsequent calls to myFunction()) however he sees fit.

Be careful, though, to either agree on a fixed size for such calls (through a global constant), or to pass the maximum size as additional parameter, lest you end up overwriting buffer limits.

like image 37
DevSolar Avatar answered Sep 20 '22 02:09

DevSolar