【问题标题】:access member of a struct in struct访问结构中结构的成员
【发布时间】:2016-02-18 06:47:03
【问题描述】:

我是 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;
}

【问题讨论】:

  • 由于comp->highest_seen_vs.view_id = 1;,给定的代码无法编译。另外,你忘了free
  • @CoolGuy 感谢您的回复。这是一个我忘记删除的虚拟变量。
  • 通过引用或指针传递应该可以解决其中一个问题。

标签: c pointers struct reference


【解决方案1】:

在 C 中调用函数时,参数是按值传递的,而不是按引用传递的。所以vs 中的view_stamp_inccomp->highest_seen_vs 的副本。在副本中递增req_id 对原始结构没有影响。

你需要传递结构体的地址。

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

...

view_stamp_inc(&comp->highest_seen_vs);

【讨论】:

    【解决方案2】:

    要更改作为参数传递给函数的原始对象,它应该通过引用传递给函数。

    例如

    static void view_stamp_inc(view_stamp *vs){
        vs->req_id++;
    };
    
    //...
    
    view_stamp_inc( &comp->highest_seen_vs );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-30
      • 2017-06-11
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多