1

I am a newbie in C. My problem is quite simple. Below is my code. I expect it to increase req_id by 1 and then pint out 1. However, the result is 0.

typedef uint32_t req_id_t;

typedef struct view_stamp_t{
    req_id_t req_id;
}view_stamp;

struct consensus_component_t{
    view_stamp highest_seen_vs;
};
typedef struct consensus_component_t consensus_component;

static void view_stamp_inc(view_stamp vs){
    vs.req_id++;
    return;
};

int main()
{
    consensus_component* comp;
    comp = (consensus_component*)malloc(sizeof(consensus_component));
    comp->highest_seen_vs.req_id = 0;
    view_stamp_inc(comp->highest_seen_vs);
    printf("req id is %d.\n", comp->highest_seen_vs.req_id);
    free(comp);
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
HuangJie
  • 1,488
  • 1
  • 16
  • 33

2 Answers2

4

When you call functions in C, parameters are passed by value, not by reference. So vs in view_stamp_inc is a copy of comp->highest_seen_vs. Incrementing req_id in the copy has no effect on the original structure.

You need to pass the address of the structure.

static void view_stamp_inc(view_stamp *vs) {
    vs->req_id++;
    return;
}

...

view_stamp_inc(&comp->highest_seen_vs);
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

To change the original object passed as an argument to a function it should be passed to the function by reference.

For example

static void view_stamp_inc(view_stamp *vs){
    vs->req_id++;
};

//...

view_stamp_inc( &comp->highest_seen_vs );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335