[Solved] Value of output is different (pointer) [closed]


Let’s look at what HardToFollow() receives and follow its flow line-by-line.

[I’ll just note right here that this code is, in fact, very hard to follow, so it’s possible I’ve made a mistake. Please follow my logic carefully to see if you agree.]

At the start of HardToFollow():

  • q-in-main = address of trouble[1] (value = 2)
  • p = address of trouble[1] (value = 2)
  • q-in-HardToFollow = copy of value of trouble[0] = 1
  • num = address of trouble[2] (value = 3)

Note that p and q-in-main are not the same variable. They are two separate pointers that point to the same location. This is because (as I’m sure is one of the points of this exercise): Variables, including pointers are passed as copies. So if you send a pointer, a new copy of the pointer is created.

*p = q + *num;

The value of the location pointed to by p is set to q-in-HardToFollow plus the value of the location pointed to by num. This is 1 plus 3, which is 4. q-in-main also points to the same location as p, so its value will also change. So now:

  • q-in-main = address of trouble[1] (value = 4)
  • p = address of trouble[1] (value = 4)

*num = q;

The value of the location pointed to by num is set to q-in-HardToFollow, which is 1. So now:

  • num = address of trouble[2] (value = 1)

num = p;

num is now set to point to the same location as p, that is, trouble[1]. So:

  • num = address of trouble[1] (value = 4)

p = &q;

p is now set to point to the location of q-in-HardToFollow. So:

  • p = address of q-in-HardToFollow (value = 1)

So the current addresses and values are:

  • q-in-main = address of trouble[1] (value = 4)
  • p = address of q-in-HardToFollow (value = 1)
  • q-in-HardToFollow = copy of value of trouble[0] = 1
  • num = address of trouble[1] (value = 4)

This works out well with the output you are getting.

1

solved Value of output is different (pointer) [closed]