1

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

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:

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);
}
4

2 回答 2

1
build_network_state(&this_router);

should be

build_network_state(this_router);

because this_routeris already of type Router *. (But &this_router is of type 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.

于 2013-11-06T19:00:14.750 回答
1

this_router is already a pointer to a router struct. You don't need to pass an address to it to build_network_state.

build_network_state(this_router);
于 2013-11-06T19:00:33.853 回答