A structure/struct is a construct that allows you to logically group variables into groups. You can then reference the group as a whole.
One place this comes in handy is if you want to pass a billion parameters to a function, but you don’t want the function declaration to be that long. Just put all the variables into a struct and pass that struct to the function.
Note that the struct itself is a new type. If you make a variable that is a struct name, its type is “struct name,” just as the number 12 is of type “int.”
One way to declare a struct:
#include <stdio.h>
struct stuff { /* declaring the type so we can use it later*/ int val; float b;};
/* Note that we dont actually have any vars of that type, yet*/
int main(void){ /* declare a variable "s" of type "struct stuff" */ struct stuff s;
s.val = 3490; /* assignment into a struct */ s.b = 3.1415;
printf("The val field in s is: %d\n", s.val);
return 0;}The compiler allows you to predeclare a struct like in the example. We can then use it later,
like we do in main() to assign values into it. When we say things like s.val = 3490, we are
using a special operator to access the val field, known as the dot operator (.).
NB: You can use the arrow (->) as an alternative to the dot (.) when working through a
pointer to a struct. It’s syntactic sugar.