我是C语言的新手,我的问题很简单。下面是我的代码。我期望它将req_id增加1,然后输出1。然而,结果是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;
}发布于 2016-02-18 14:54:21
在C中调用函数时,参数按值传递,而不是按引用传递。所以view_stamp_inc中的vs是comp->highest_seen_vs的副本。在副本中递增req_id不会对原始结构产生影响。
您需要传递结构的地址。
static void view_stamp_inc(view_stamp *vs) {
vs->req_id++;
return;
}
...
view_stamp_inc(&comp->highest_seen_vs);发布于 2016-02-18 14:53:52
要更改作为参数传递给函数的原始对象,应通过引用将其传递给函数。
例如
static void view_stamp_inc(view_stamp *vs){
vs->req_id++;
};
//...
view_stamp_inc( &comp->highest_seen_vs );https://stackoverflow.com/questions/35474643
复制相似问题