[Solved] Cannot get pointers result


I can only assume, that an expected behavior is to get variable v incremented 10 times using pointer.

If that’s correct, you have two mistakes:

  1. Type of pointer should be the same with the data you’re pointing. If you’re pointing at int variable, you should use int * pointer.
  2. In the for loop condition: at each iteration you’re incrementing both i and p (i++,p++).
    When you’re incrementing pointer, it moves to the next memory cell (in simple words, actually it’s a bit complicated).
    If you want to work with variable v only, you should not modify the pointer itself, only the variable it refers to.
    Thus, if you’ll remove p++ part , you’ll get 11, 12, 13, ... as a result.

Why it shows such a weird results now? Just because at each iteration you’re changing pointer (thus it refers to other memory cell). Memory that pointer refers to after increment may contain random data, which we are able to see. However, such an approach contains undefined behavior, and results may vary. It may even end with termination of the program.

However, it’s indeed not clear what behavior are you expecting to get, and if you’ll clarify that more, I guess community will be able to help you more.

3

solved Cannot get pointers result