+ 2

Question about a code

Here is the code: "#include <iostream> using namespace std; int main() { int a[5]={1,2,3,4,5}; int *p=a; for(int i=0; i<5; i++) { a[i]=i; cout << *p; } return 0; }" This code outputs "00000" when I was expecting "01234" Why does this happen? "*p" is pointing at "a." Outputting a variable for an array without the brackets outputs a memory address. So shouldn't the output be a memory address? 00000 seems like a strange output...

8th Jun 2017, 2:13 AM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
7 Answers
+ 9
Because p points at the beginning of the array, which holds the value 0. It returns 0 everytime because you don't increment p.
8th Jun 2017, 2:18 AM
Karl T.
Karl T. - avatar
+ 8
"Pointing to" means to hold its address, not the value itself. "a" in the second case is an array of integers, not an integer. You can think of arrays as being simplified pointers - which is why you don't need the "&" before "a". It is already a memory location.
8th Jun 2017, 3:13 AM
Karl T.
Karl T. - avatar
+ 7
cout << (*p + i);
8th Jun 2017, 2:22 AM
jay
jay - avatar
+ 7
Pointer values can vary because they hold a memory address, which can be incremented/decremented just like an integer. And they can point to an integer, a float, a bool etc.
8th Jun 2017, 2:46 AM
Karl T.
Karl T. - avatar
+ 2
I didn't know that. Thanks Helioform. But does this mean pointers are constant no matter what? And why can a pointer point to an array but not an integer? Sorry I'm still new to this.
8th Jun 2017, 2:42 AM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
+ 1
I'm testing it, but it seems the compiler on this site doesn't let me point directly to an integer. I can say "int *p=&i" but not "int *p=i." On the other hand I can say "int *p=a" for an array "a", but not int *p=&a". What does this mean?
8th Jun 2017, 3:09 AM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
+ 1
Thanks Helioform, I'm getting the hang of it.
8th Jun 2017, 3:25 AM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar