Home > Back-end >  Is it possible to pass struct members In a function in c?
Is it possible to pass struct members In a function in c?

Time:11-21

For example I have the following definition of a struct in a header file; Edit: All of this is it in C.

struct characterPlayer
{
    int pozPx;
    int pozPy;
};

And the function definition:

void caracterMoveDown(struct characterPlayer &player1.pozPx,struct characterPlayer &player1.pozPy);

And when I try to compile I get the following error:

"error: expected ',' or '...' before '.' token"

Am I doing the impossible somewhere ? Thank you very much for the help;

I tried to initialise the player1 in the header and after that to put it in the function..no succes. I want to work with those arguments because they will be modified in the function and want to keep the new value they will get . That is why I put "&" ;

CodePudding user response:

First of all, C does not have references so you can't use & to take them by reference.

You can use pointers instead.

If you want to take pointers to the individual variables as arguments:

void caracterMoveDown(int *pozPx, int *pozPy) {
    *pozPx = ...;
    *pozPy = ...;
}

int main(void) {
    struct characterPlayer foo;
    caracterMoveDown(&foo.pozPx, &foo.posPy);
}

If you want to take a pointer to the whole struct:

void caracterMoveDown(struct characterPlayer *player1) {
    player1->pozPx = ...;
    player1->pozPy = ...;
}

int main(void) {
    struct characterPlayer foo;
    caracterMoveDown(&foo);
}
  • Related