C Structs and Typedef
Structs
Declaring a struct
struct car { char *name; float price; int speed;};
int main(void){ struct car saturn; saturn.name = "Saturn SL/2"; saturn.price = 15999.99; saturn.speed = 175;}
- Commonly used with
typedef
#include <stdio.h>
typedef struct { char *name; int leg_count, speed;} animal;
int main(void){ animal z;}
Passing structs to functions
- It’s far more common to pass a pointer to a struct to a function
void set_price(struct car *c, float new_price){ // This won't work because dot operator only works on `struct`, not pointer to struct // c.price = new_price; c->price = new_price;}
int main(void){ struct car saturn = {.speed=175, .name="Saturn SL/2"}; set_price(&saturn, 799.99); printf("Price: %f\n", saturn.price);}
Arrow Operator
void set_price(struct car *c, float new_price){ // This won't work because dot operator only works on `struct`, not pointer to struct // c.price = new_price;
// This works but it's non-idiomatic // (*c).price = new_price; c->price = new_price;}
Padding bytes
- C is allowed to add padding bytes within of after a
struct
as it sees fit. They’re not committed to be directly adjacent in memory.
#include <stdio.h>#include <stdlib.h>#include <string.h>
struct foo { int a; char b;};
int main(){ printf("%zu\n", sizeof(int)+sizeof(char)); printf("%zu\n",sizeof(struct foo));}
- To findout where those structure are
#include <string.h>#include <stddef.h>
struct foo { int a; char b; int c; char d;};
int main(){ printf("%zu\n", offsetof(struct foo, a)); printf("%zu\n", offsetof(struct foo, b)); printf("%zu\n", offsetof(struct foo, c)); printf("%zu\n", offsetof(struct foo, d)); // 0 4 8 12}