Skip to content
thesarfo

Note

C: Pointers to Struct

Why you'd pass a pointer to a struct instead of the struct itself, and the arrow operator syntactic sugar.

views 0

How do you pass structs around to other functions and stuff? You probably want to pass a pointer to the struct instead of the struct itself. Why?

When you pass parameters to functions, EVERY PARAMETER WITHOUT FAIL gets copied onto the stack when you call a function! So if you have a huge struct that’s like 80,000 bytes in size, it’s going to copy that onto the stack when you pass it. That takes time.

Instead, why not pass a pointer to the struct? The pointer also gets copied onto the stack — sure does, but a pointer is, these days, only 4 or 8 bytes, so it’s much easier on the machine, and works faster.

And there’s even a little bit of syntactic sugar to help access the fields in a pointer to a struct. Syntactic sugar is a feature of a compiler that simplifies the code even though there’s another way to accomplish the same thing.

Here’s an example wherein we have a struct variable, and another variable that is a pointer to that struct type, and some usage for both:

#include <stdio.h>
/* declare the type so we use it later */
struct antelope{
int val;
float something;
};
int main(void){
struct antelope a;
struct antelope *b; /*a pointer to a struct antelope*/
b = &a; /* pointing b at a */
a.val = 3490;
/* since its a pointer, we have to dereference it before we can use it*/
(*b).val = 3491;
/* but that looks kinda bad, so let's do the exact same thing except this time we'll use the "arrow operator", which is a bit of syntactic sugar: */
b->val = 3491; /* exactly the same as (*b).val=3491*/
return 0;
}