DEV Community

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

Posted on

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. And the harder I thought, the deeper I went down a rabbit hole of confusion. Asking for AI did not help.
I will give the example that stumped me, some of the mistakes I made, why they were wrong and the principles that I learned from this experience.
Spoiler, in the end I went back to the introduction to pointers in my course material, and thinking in this simplistic way decluttered my brain and the answer became clear.

Here is the 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;
}
`

This code will output the following.
**r = 12
**s = 80
x = 92
*p = -7
*q = 75
a = 75
b = -7

These are the mistakes I made;
I returned an int value of 64 (not 92) back to main from function f. In lines 5 and 6, the pointers are dereferenced to the int values of 80 and 12 respectively. But I mistakenly believed that the arithmetic on **r and **s affected the final value of temp and temp2 not realizing that those initializations in lines 5 and 6 are locked into the memory addresses of temp and temp2 and to manipulate those values I would need to explicitly perform arithmetic on temp and temp2. e.g. temp += 3.

Again, I changed the wrong addresses. Instead of changing what *r and *s points to within the function f stack, I changed what *p and *q point to in the main stack.

Finally, I forgot that *z was a pointer to an int. So, I was thinking that I had to perform arithmetic on the address at *p. So, I believed that *z += 3 meant *z = &p + 3. My thinking was that if I was supposed to perform arithmetic on int a, then the expression at line 7 would be *z = **r. This one got me so confused and going around in circles.

My take-aways;
Go back to basics.
Write out every step, even if it seems straight forward or insignificant.
Remember what the type is
Visualize the memory addresses

Top comments (0)