AndroidDev
AndroidDev

Reputation: 21237

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

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

Upvotes: 1

Views: 12351

Answers (2)

shf301
shf301

Reputation: 31404

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

Upvotes: 1

ouah
ouah

Reputation: 145899

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.

Upvotes: 1

Related Questions