/* * CSE 303/374 demo program - structs * Basic operations with structs and pointers */ /* Struct declaration */ struct Point { int x; int y; }; /* basic struct usage */ int main() { /* allocate a struct Point */ struct Point q; q.x = 1; q.y = 2; struct Point p; /* set its fields */ p.x = 4; p.y = 3; /* read its fields */ int v = p.x; /* pointer to a struct */ struct Point* r; r = &p; /* access fields through pointer */ int cx = (*r).x; int cy = r->y; r->y += 2; } void print_point(struct Point p) { p.x+=1; printf("%d %d\n", p.x, p.y); } int main() { struct Point t; print_point(t); } /* Point is now a known struct tag, but is _not_ a type */ /* (could use a typedef if we wanted, but not used here) */ /* Function prototypes */ void init_point(struct Point *p); struct Point new_point(); /* Function definitions */ void f() { struct Point p1, p2; init_point(&p1); p2 = new_point(); // equivalent, potentially slower } void init_point(struct Point *p) { p->x = 0; (*p).y = 0; } struct Point* dangling_point() { struct Point ans; ans.x = 0; ans.y = 0; return &ans; // *really* bad idea, later dereference will hopefully crash! } struct Point new_point() { struct Point ans; ans.x = 0; ans.y = 0; return ans; // no problem } void wrong_update_x(struct Point p, int new_x) { // this function has no effect on anything p.x = new_x; } void update_x(struct Point * p, int new_x) { // updates field in struct referenced by p p->x = new_x; }