my effort to understand pointers better, I wrote this code:
int *a = 17;
printf("%d", a+3);
It compiled fine under c using gcc-4.3.4: http://ideone.com/abotd
And yet it failed to compile with c++: http://ideone.com/IdGHy
I would like to know why.
Also, the output, as you can see from the first link is 29. I pseudo-understand what’s happening: sizeof(int) is 4, and when I wrote a+3 instead of adding 3 to 17, 3*4 is being added.
Still, I would appreciate if someone can explain it more eloquently.
Thanks!
For C++ version try this:
And yes your explanation is correct…
This is called pointer arithmetic and works the way you said. Note however that the code you are using here where you assign a constant value to a pointer to an
intis rarely done in real life. The pointer value usually comes from some kind of memory allocation functions e.gmallocin C ornewin C++ (althoughnewisn’t a function).