Define and return structure in c

I am trying to convert code from Javascript to c. The function creates an array (which always has a fixed number of elements), and then returns an array. I found out that c is not easy to return an array, so I would like to return this as a structure instead. My c is not so good, so I would like to check that returning the structure is what needs to be done in this situation, and that I am doing it right. Thank.

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
source share
4 answers

This is fine and correct for C, but passing a structure by value may not be a good idea for large structures or if you intend to change the structure in the caller:

Xyz s;
s = XyzPlusOne( s );

:

Xyz s;
XyzPlusOne( & s );

, - :

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

.

+8

, , , , const- , :

Xyz xyzPlusOne(const Xyz* addOne) { 

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

    return xyz;
}

, ( ):

void xyzPlusOne(Xyz* addOne) { 
    addOne->x++;
    addOne->y++;
    addOne->z++;
}
+3

, , -C- . C .

+2

, :

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

: xyzPlusOne (& array);

+2

Source: https://habr.com/ru/post/1749391/


All Articles