Skip to content
thesarfo

Note

C: Struct Pointers to Functions

Passing struct pointers to functions so modifications are visible back in the caller.

views 0

Passing struct pointers to functions:

#include <stdio.h>
struct mutantfrog
{
int num_legs;
int num_eyes;
};
void build_frog(struct mutantfrog *f){
f->num_legs = 10;
f->num_eyes = 1;
}
int main(void){
struct mutantfrog ernest;
build_frog(&ernest); /* passing a pointer to the struct */
printf("Leg count: %d\n", ernest.num_legs); /* prints 10*/
printf("Eyes count: %d\n", ernest.num_eyes); /* prints 1*/
return 0;
}

Another thing to note here: if we passed the struct instead of a pointer to the struct, what would happen in the function build_frog() when we changed the values? That’s right: they’d only be changed in the local copy, and not back out in main(). So, in short, pointers to structs are the way to go when it comes to passing structs to functions.