#include<iostream>
using namespace std;
void passPointer(int *pointer)
{
cout << *pointer;
}
int main()
{
int *iNum = new int(25);
passPointer(iNum);
return 0;
}
Can someone explain to me why when I use the passPointer() function in main, it has to be passPointer(iNum) but not passPointer(*iNum)? Is it because I am dereferencing it at the parameter if I use *? Please explain as detailed as you can as I am a bit confused.
Thanks guys.
I am very sympathetic to these sorts of questions, because this is one of the only things that I had trouble with when learning C++.
The basic problem is that in the syntax of C++, the
*and&characters are used for many different things with similar but subtly different meanings.In your case, you are considering using
*in four different places.In the first place:
int *iNum = new int(25);, the*is sitting in a declaration. This means that is is a type annotation saying thatiNumis a pointer.In the second place:
passPointer(*iNum);, the*is sitting in an expression. This means that it is the dereference operator, which means: “get the value pointed to byiNum“. In this case the value pointed to byiNumis anint. As you will see later,passPointeris declared to take an argument of typepointer to int, so you cannot pass a plainintas an argument topassPointer. You should instead just passiNum(asiNumis a pointer to int).In the third place:
void passPointer(int *pointer), the*is again sitting in a declaration. This means that it has the same meaning as in the first place – it says thatpointeris a pointer (toint).In the fourth place:
cout << *pointer;, the*is again sitting in an expression. This means that, as in the second case, it is saying “dereferencepointerand get the value thatpointeris storing the address of”.