How a simple pointer exercise had me pulling my hair out.
Source: Dev.to

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
-
Incorrect return value – I returned
64instead of92.
In lines 5 and 6,tempandtemp2are initialized with the values ofr(a pointer) and**s(the integer12). I mistakenly thought that later arithmetic on**rand**swould affecttempandtemp2. Those variables are independent copies; to change them I would need to modifytempandtemp2directly (e.g.,temp += 3). -
Changed the wrong addresses – I altered what
*pand*qpoint to inmaininstead of what*rand*spoint to insidef. The swap should affect the pointers passed to the function, not the original variables. -
Misunderstood
*z– I treated*zas an address and thought*z += 3meant “move the pointer three positions”. In reality,*zis anint(the value pointed to byz), so*z += 3adds3to 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.