Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a 2D char array in C

I messed around with this enough but I really don't get it.

Here is what I want to do: Take a 2D char array as an input in a function, change the values in it and then return another 2D char array.

That's it. Quite simple idea, but ideas do not get to work easily in C.

Any idea to get me started in its simplest form is appreciated. Thanks.

like image 300
Dave Avatar asked Dec 07 '22 18:12

Dave


1 Answers

C will not return an array from a function.

You can do several things that might be close enough:

  • You can package your array in struct and return that. C will return structs from functions just fine. The downside is this can be a lot of memory copying back and forth:

    struct arr {
        int arr[50][50];
    }
    
    struct arr function(struct arr a) {
        struct arr result;
        /* operate on a.arr[i][j]
           storing into result.arr[i][j] */
        return result;
    }
    
  • You can return a pointer to your array. This pointer must point to memory you allocate with malloc(3) for the array. (Or another memory allocation primitive that doesn't allocate memory from the stack.)

    int **function(int param[][50]) {
        int arr[][50] = malloc(50 * 50 * sizeof int);
        /* store into arr[i][j] */
        return arr;
    }
    
  • You can operate on the array pointer passed into your function and modify the input array in place.

    void function(int param[][50]) {
        /* operate on param[i][j] directly -- destroys input */
    }
    
  • You can use a parameter as an "output variable" and use that to "return" the new array. This is best if you want the caller to allocate memory or if you want to indicate success or failure:

    int output[][50];
    
    int function(int param[][50], int &output[][50]) {
        output = malloc(50 * 50 * sizeof int);
        /* write into output[i][j] */
        return success_or_failure;
    }
    

    Or, for the caller to allocate:

    int output[50][50];
    
    void function(int param[][50], int output[][50]) {
        /* write into output[i][j] */
    }
    
like image 137
sarnold Avatar answered Dec 24 '22 13:12

sarnold