How a simple pointer exercise had me pulling my hair out.

Published: (January 30, 2026 at 04:31 PM EST)
3 min read
Source: Dev.to

Source: Dev.to

Cover image for How a simple pointer exercise had me pulling my hair out.

I was tasked to write out (by hand) the outputs for a given pointer exercise. It seemed simple enough, but when I got to a certain stage, I found myself lost. The harder I thought, the deeper I went down a rabbit hole of confusion. Asking an AI did not help.

Below is the example that stumped me, the mistakes I made, why they were wrong, and the principles I learned from this experience.

Code

int f(int** r, int** s) {
    int temp = r;
    int temp2 = **s;
    int *z = *r;
    *r = *s;
    *s = z;
    printf("r = %d\n", r);
    printf("s = %d\n", **s);
    *z += 3;
    **s -= 8;
    **r -= 19;
    return temp + temp2;
}

int main(void) {
    int a = 80;
    int b = 12;
    int *p = &a;
    int *q = &b;
    int x = f(&p, &q);
    printf("x = %d\n", x);
    printf("*p = %d\n", *p);
    printf("*q = %d\n", *q);
    printf("a = %d\n", a);
    printf("b = %d\n", b);
    return EXIT_SUCCESS;
}

Expected Output

r = 12
s = 80
x = 92
*p = -7
*q = 75
a = 75
b = -7

Mistakes I Made

  1. Incorrect return value – I returned 64 instead of 92.
    In lines 5 and 6, temp and temp2 are initialized with the values of r (a pointer) and **s (the integer 12). I mistakenly thought that later arithmetic on **r and **s would affect temp and temp2. Those variables are independent copies; to change them I would need to modify temp and temp2 directly (e.g., temp += 3).

  2. Changed the wrong addresses – I altered what *p and *q point to in main instead of what *r and *s point to inside f. The swap should affect the pointers passed to the function, not the original variables.

  3. Misunderstood *z – I treated *z as an address and thought *z += 3 meant “move the pointer three positions”. In reality, *z is an int (the value pointed to by z), so *z += 3 adds 3 to that integer, not to the address.

These misunderstandings sent me around in circles.

Takeaways

  • Go back to basics – Re‑read introductory material on pointers.
  • Write out every step – Even seemingly trivial operations can hide subtle details.
  • Remember the type – Knowing whether you’re dealing with a pointer, a pointer to a pointer, or an actual value is crucial.
  • Visualize memory addresses – Sketching the layout helps avoid confusing values with addresses.
Back to Blog

Related posts

Read more »

Day-4 Data Types

Data types Data types are the kinds of information stored in a variable e.g., numbers, characters, true/false, etc.. There are two categories of data types: -...