[英]Passing a pointer to a struct as a function argument
I'm trying to pass a pointer to a struct over to a separate function. 我正在尝试将指向结构的指针传递给单独的函数。 But when I go to compile, I get
warning: passing argument 1 of 'build_network_state' from incompatible pointer type
但是当我去编译时,我得到
warning: passing argument 1 of 'build_network_state' from incompatible pointer type
This is in a helper function the compiles into my program: 这是在一个辅助函数中编译到我的程序中:
typedef struct router {
int num;
char label[64];
Topology *topology;
} Router;
This is from the .c file: 这是来自.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);
}
build_network_state(&this_router);
should be 应该
build_network_state(this_router);
because this_router
is already of type Router *
. 因为
this_router
已经是Router *
类型。 (But &this_router
is of type Router **
) (但
&this_router
的类型为Router **
)
And 和
Router* this_router = malloc(sizeof(Router));
should be 应该
Router* this_router = malloc(sizeof *this_router);
You want to allocate the size of the structure object, not the size of the pointer to the structure object. 您要分配结构对象的大小,而不是结构指针的大小。
this_router
is already a pointer to a router struct. this_router
已经是一个指向路由器结构的指针。 You don't need to pass an address to it to build_network_state
. 您无需将地址传递给
build_network_state
。
build_network_state(this_router);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.