views:

102

answers:

4

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;
}
+3  A: 

This looks like it will work with a modern compiler, but it's an un-C-like approach. In C you would be much more likely to pass the struct by reference and return nothing.

Artelius
Thanks, I wasn't aware of this.
nevan
+3  A: 

That should work fine, although if you want to keep the original struct intact, you may want to have it pass a const pointer to the struct to avoid making another copy of it:

Xyz xyzPlusOne(const Xyz* addOne) { 

    Xyz xyz;
    xyz.x = addOne->x + 1;
    xyz.y = addOne->y + 1;
    xyz.z = addOne->z + 1;

    return xyz;
}

Or you could pass a regular pointer to the struct, change it in the function, and not return anything (if you don't need to keep the original struct intact):

void xyzPlusOne(Xyz* addOne) { 
    addOne->x++;
    addOne->y++;
    addOne->z++;
}
Eric Petroelje
You screwed it up again >_< (see my edit)
Artelius
@Artelius - Doh, I think I got it right now. Been a while since I've done any C programming :)
Eric Petroelje
Change "." to "->", since you're referencing through a pointer.
TMN
+6  A: 

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:

Xyz s;
s = XyzPlusOne( s );

in which case you would be better off passing the structure as a pointer and simply saying:

Xyz s;
XyzPlusOne( & s );

On the other hand, if you want something like this:

Xyz s1, s2;
...,
s2 = XyzPlusOne( s1 );

then returning a value makes sense.

anon
+2  A: 

Here is another approach that just modifies the original array:

void xyzPlusOne(Xyz *addOne)
{ 
    if (addOne != NULL)
    {
        addOne->x++;
        addOne->y++;
        addOne->z++;
    }
}

call as: xyzPlusOne(&array);

Amardeep