+ 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...
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.
+ 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.
+ 7
cout << (*p + i);
+ 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.
+ 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.
+ 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?
+ 1
Thanks Helioform, I'm getting the hang of it.