I’m trying to convert some code from Javascript to c. The function creates an array (which always has a fixed number of items) and then returns the array. I’ve learned that in c it’s not straightforward to return an array, so I’d like to return this as a struct instead. My c is not all that great, so I’d like to check that returning a struct is the right thing to do in this situation, and that I’m doing it the right way. Thanks.
typedef struct {
double x;
double y;
double z;
} Xyz;
Xyz xyzPlusOne(Xyz addOne) {
Xyz xyz;
xyz.x = addOne.x + 1;
xyz.y = addOne.y + 1;
xyz.z = addOne.z + 1;
return xyz;
}
It’s perfectly good and correct C, but passing the structure by value may not be a good idea for larger structures or if you intend to change the structure in the caller:
in which case you would be better off passing the structure as a pointer and simply saying:
On the other hand, if you want something like this:
then returning a value makes sense.