【问题标题】:Passing a pointer to a struct as a function argument将指向结构的指针作为函数参数传递
【发布时间】:2013-11-18 04:26:45
【问题描述】:

我正在尝试将指向结构的指针传递给单独的函数。但是当我去编译时,我得到warning: passing argument 1 of 'build_network_state' from incompatible pointer type

这是编译到我的程序中的辅助函数:

typedef struct router {
    int num;
    char label[64];
    Topology *topology;
} Router;

这是来自 .c 文件:

void build_network_state(Router *ptr) {

    fprintf(stdout, "Hello from router %s\n", ptr->label);
}

int main(int argc, char *argv[]) {

    Router* this_router = malloc(sizeof(Router));

    ...

    fprintf(stdout, "test: %s\n", this_router->label); // output looks fine if I comment the next line
    build_network_state(&this_router);
}

【问题讨论】:

  • @chux 不,不完全是。那是因为this_router 已经是Router * 类型。不需要addressof操作符。
  • @H2CO3 恭喜100K
  • @chux 没问题。无论如何,请在此处留下我的评论作为 OP 的信息。
  • @chux 哦,谢谢。 :-)

标签: c pointers struct pass-by-reference


【解决方案1】:
build_network_state(&this_router);

应该是

build_network_state(this_router);

因为this_router已经是Router *类型。 (但&this_routerRouter ** 类型)

Router* this_router = malloc(sizeof(Router));

应该是

Router* this_router = malloc(sizeof *this_router);

您要分配结构对象的大小,而不是指向结构对象的指针的大小。

【讨论】:

  • 不客气。 +1 无论如何解释问题。
  • @ouah 谢谢! :) 花了很长时间。 :P
  • 是的,我知道这个问题会让 C 专家争先恐后地跑到键盘上看谁能先回答!再次感谢!
【解决方案2】:

this_router 已经是一个指向路由器结构的指针。您无需将地址传递给build_network_state

build_network_state(this_router);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 2021-07-17
    • 2019-08-17
    相关资源
    最近更新 更多