I'm currently in programming 2 at my college. We have a test coming up and just wanted to ask for some confirmation on a few things I put together on pointers. Consider the following code:
//CASE 1
int Awesome = 10; //Line 1
int *P = &Awesome; //Line 2
cout << Awesome << endl; //Line 3
cout << *P << endl; //Line 4
//CASE 2
int X[3]={0,0,5}; //Line 1
int *A = X; //Line 2
cout << X[2] << endl; //Line 3
cout << A[2] << endl; //Line 4
Here's where my questions come in, but I think I sort of "stumbled" onto the answers of my questions, but I want to make sure its correct.
In the first line 2, I declare pointer P
and give it Awesome
's address by using the reference operator. In the second line 2, I declare pointer A
and give it the address of X
. I never understood why we didn't use the &
operator in the case of giving an array address to a pointer. After thinking about it, I recall hearing that the array name is just a constant pointer containing the address the first subscript of the array. If thats correct, then it would make sense why we wouldn't need to use the &
to obtain the address of the array, because the array name itself already contains the address. Is this correct?
My second question. In the first line 4, I'm cout
-ing the contents of what pointer P
is pointing at by using the dereference operator, but in the second 4th line, I don't need to use the *
operator to obtain the value. In my head, I wasn't sure why it differed, but I think the concept in the paragraph above made it more clear. The array name itself and a pointer are basically the same thing (except the array name is a constant pointer I think). An array name is a constant pointer that holds the address and the pointer is getting this address. Therefore, we use the new pointer holding the new address the same way. Its not the same as the first instance at all. Since an array name and a pointer are basically the same, we don't need to use the special *
operator, just use it like a normal array with array notation. Is this correct?
I've been struggling to understand why the two concepts above differed, why in one instance (int *P = &Address
) we needed to use the &
operator to give an address and why in another instance (int *A=X
) we didn't. And I was struggling with why we use the *
in one instance (cout << *P;
) and not in another (cout << A[2];
). The differences had me very confused, but if I'm anywhere close to being correct with my logic, it makes total sense now. Can anyone confirm this or correct it if its entirely wrong?