Yoakain
Yoakain

Reputation: 15

How to modify a value of a struct within a function? [C]

Let's see this code as an example

#include <stdio.h>
typedef struct 
{
    int hp;
}Player;

void lessHp(Player a)
{
    printf("a.hp = %d\n", a.hp);
    (*Player) -> hp -= 1;
    printf("a.hp now = %d\n", a.hp);
}

int main()
{
    Player a;
    a.hp = 1;
    lessHp(a);
    printf("a.hp = %d\n", a.hp);
    return 0;
}

Now, what this program prints is:

a.hp = 1
a.hp now = 0
a.hp = 1

But how can I make it so that the lessHp function would actually be able to substract 1 from that value? When trying to do it by reference it tells me to use ("->"), but I really, really don't know what that is (I've only used simple pointers, the only thing that I've handled with pointers is dynamic memory allocation).

Upvotes: 0

Views: 133

Answers (1)

Rivasa
Rivasa

Reputation: 6750

You need to use a pointer instead of passing a copy. (That is you should be editing original.) You can fix like so:

#include <stdio.h>
typedef struct 
{
    int hp;
} Player;

void lessHp(Player* a)
{
    printf("a.hp = %d\n", a->hp);
    a->hp -= 1;
    printf("a.hp now = %d\n", a->hp);
}

int main()
{
    Player a;
    a.hp = 1;
    lessHp(&a);
    printf("a.hp = %d\n", a.hp);
    return 0;
}

With an output of:

a.hp = 1
a.hp now = 0
a.hp = 0

Upvotes: 2

Related Questions