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.
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
structandreturnthat. C will returnstructs from functions just fine. The downside is this can be a lot of memory copying back and forth: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.)You can operate on the array pointer passed into your function and modify the input array in place.
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:
Or, for the caller to allocate: