Struct Pointer Parameter in C

Level 4223 keystrokes

Passes struct by pointer to modify the original structure in a function.

C code

// Define Point type using typedef
1typedef struct {
2 int x, y;
3} Point;
4
// Function takes pointer to modify original
5void move(Point *p, int dx, int dy) {
// p->x changes the caller's struct, not a copy
6 p->x += dx;
7 p->y += dy;
8}
9
// Create a point
10Point pt = {10, 20};
// Print original position
11printf("Before: (%d, %d)\n", pt.x, pt.y);
// Pass address to modify original
12move(&pt, 5, -3);
// The original changed: (10+5, 20-3) = (15, 17)
13printf("After: (%d, %d)\n", pt.x, pt.y);

Output

Before: (10, 20)
After: (15, 17)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ,× 12
  • ;× 8
  • (× 6
  • )× 6
  • .× 4
  • "× 4
  • %× 4
  • -× 3
  • {× 3
  • }× 3

More C examples at level 4

← C typing practice