Reputation: 2732
I know what a struct is, and how to make one and why you should typedef one...
typedef struct Foo {
int a;
char b;
float c;
} Foo;
But I don't know how it works. Is the template saved on the stack and used like a lookup table when you reference an element (similar to how classes work)? Or is there another design at play here.
Upvotes: 0
Views: 923
Reputation: 48290
A struct
is just a definition. It defines an arrangement of data, but it's not saved within your program itself unless you declare a variable of that type. The variable can be stored on the stack, on the heap, or even in registers if it's small enough ... according to the same rules that are used for other variables.
Upvotes: 1
Reputation: 9930
The part about typedef-ing structs is debatable.
Structs are basically a convenient way to store a bunch of data together.
The compiler knows which offsets point to which element and bakes them into the program when it needs to access an element. Because the struct structure can't change during run time, there's no need to use a look up table.
For example, I could write the above struct like the following:
char Foo[12];
*((int *) (Foo + 0)) = a;
*((char *) (Foo + 4)) = b;
*((float *)(Foo + 8)) = c;
You can see the offsets are baked in manually. There's no need for a lookup table. When you use a struct, the compiler does pretty much the same thing automatically.
Upvotes: 5