Daniel Hazeley Daniel Hazeley -4 years ago 94
C Question

Pass struct into function as its individual attributes

I want to pass a structure into a (recursive) function and each time it calls the function I want to change the values of the attributes it gets without updating the actual values in the previous scope.

Here is some sample code. Would this be a correct way to implement this? (Specific help needed on the function call in the "Function" file.

Header File

typedef struct Pos {
int x;
int y;
} Pos;

bool func1(Pos vars, int step);


Main

int main(int argc, char ** argv) {
Pos vars = {.x = 0, .y = 0};

if (func1(vars, 0)) {
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}


Function

bool func1(Pos vars, int step) {
if (step == 2) {
return true;
}

func1({.x += 1, .y += 2}, step+1);

printf("%d %d", vars.x, vars.y);

return true;
}

Answer Source

You need to use a 'compound literal', which looks like a cast before an initializer:

bool func1(Pos vars, int step) {
    if (step == 2) {
        return true;
    }

    func1((Pos){.x = vars.x + 1, .y = vars.y + 2}, step+1);

    printf("%d %d", vars.x, vars.y);

    return true;
}

This feature was added to C99 — but since you're attempting to use designated initializers, that presumably isn't a problem to you.


I see that BLUEPIXY pointed out this notation in a comment that I didn't read until after adding this answer.
I've made this Community Wiki.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download