A struct groups named members of possibly different types into one object. It is C’s composite data before any “OOP.” There is no inheritance. There are no methods — only functions that take a struct or a pointer to one.
struct point {
int x;
int y;
};
struct point p = {3, 4};
p.x = 5;
Mental model: a struct value is the members laid out in order (with possible padding). p.x is a member. sp->x is a member through a pointer. Assignment copies the whole struct (all members).
sizeof(struct point) may be larger than the sum of member sizes. Do not send a struct over the network by dumping bytes unless you have a packed protocol (Wave B).offsetof(type, member) from <stddef.h> when you need an offset.struct mixed {
char c;
int n; /* likely 3 bytes of padding before n on a 32/64-bit ABI */
};
struct point p = {0}; /* all zero */
struct point q = {.y = 2}; /* C99 designated; x is 0 */
struct point r = {.x = 1, .y = 2};
int.typedef struct point point;
/* or in one go */
typedef struct node {
int v;
struct node *next; /* tag required for self-reference */
} node;
struct point) and a typedef name are different namespaces. You can have both.typedef pointers as a hiding trick (typedef struct node *Node) in Wave A — it hides * from readers.struct point translate(struct point p, int dx, int dy) {
p.x += dx;
p.y += dy;
return p; /* copy in, copy out */
}
void translate_p(struct point *p, int dx, int dy) {
if (p == NULL) {
return;
}
p->x += dx;
p->y += dy;
}
const struct point * if the function only reads.p.x vs p->x until it compiles — know which you have.== — not allowed. Compare members, or memcmp only if you accept padding noise.struct opaque; is useful for hiding, but you cannot declare a value of an incomplete type — only a pointer.{0} or designated initializers.-> only on pointers. Use . on values.const T * for read-only large objects.* visible.~ Good luck with your revision! ~