Pointer Issues | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pointer Issues

#include <iostream> using namespace std; int x = 5; int *p = &x; int main() { *p++; cout << *p; return 7; } Whenever I run the above code I get this Output 4947972. I'd have thought since I pointed to 'int x' that the increment would cause an increment in x certainly not this integer I'm getting. Why 4947972 & not 6.

5th Jun 2018, 10:31 AM
Grandad
Grandad - avatar
4 Answers
+ 7
edit as int *p=&x;
5th Jun 2018, 10:38 AM
Scooby
Scooby - avatar
+ 4
I have seen a similar case a while ago, as I recall the solution was to use parentheses to the increment statement, so to lift the precedence, unfortunately I couldn't find that thread, and I can't explain it as good as they did there, anyways it goes like: (*p)++; With pre-increment it is: ++*p; Hth, cmiiw
5th Jun 2018, 12:17 PM
Ipang
+ 2
My bad, I skipped that in the description.... But yeah it was already 'int *p = &x;' in my code
5th Jun 2018, 10:43 AM
Grandad
Grandad - avatar
+ 1
I'm guessing it has to do with the increment of '*p' changing the address '*p' points to, don't know if this makes sense but I just don't wanna keep guessing.
5th Jun 2018, 10:52 AM
Grandad
Grandad - avatar