0

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).

3
  • 2
    pass a reference, not a copy Commented Apr 29, 2018 at 3:13
  • 1
    C passes arguments by value. When you give just a struct, it passes the value of the struct (a copy of it). Giving a pointer passes the location of your original struct, so you can write modifications at that location. Commented Apr 29, 2018 at 3:18
  • 1
    What is this (*Player) -> hp -= 1;? This does not compile, doesn't it? Commented Apr 29, 2018 at 10:08

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. You saved me a lot of hassle.
@Yoakain opening a book in ten first pages takes less time, than wainting help from web
I read a lot before asking for help, did not find my answer + I needed it quick. Your advice could've been helpful otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.