← The C Language Lesson 42 of 77 · 10 XP

Structs and pointers

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Big structs are passed to functions by pointer: that way no extra bytes are copied, and the function can change the original.

void move(struct point *p, int dx, int dy)
{
    (*p).x += dx;      // this works, but it's awkward
    p->y += dy;        // the arrow: the same as (*p).y
}

struct point a = {0, 0};
move(&a, 2, 3);        // a = {2, 3}

The -> operator means "a struct field through a pointer". You'll see it all the time: in linked lists, trees, the Linux kernel.

If a function only reads the struct, pass const struct point *p. That guarantees the function won't change it.

Task. Describe struct account { int id; int balance; } and a function int withdraw(struct account *acc, int amount). If there's enough money, it deducts the amount and returns 1; otherwise it returns 0 and changes nothing. The program reads the starting balance and several amounts until the end of the input, prints ok or fail after each one, and the final balance at the end.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.