Reputation: 9
I have tried this piece of code mentioned below, I'm not understanding why *p
need to be pass to doOperation()
function. Why can't we pass p
? What is the difference between the two?
doOperation(*p); // need explanation why derefencing
doOperation(p); // Gives compilation error
int main()
{
int *p = getpointer();
std::cout << "p:" << *p << std::endl;
doOperation(*p); // Why this has to be pass as a pointer when the function parameter as reference
return 0;
}
void doOperation(int &ptr)
{
//std::cout << "ptr:" << ptr << std::endl;
}
int *getpointer()
{
int *ptr = new int[10];
int i;
for (i=0; i <= 10; i++)
{
*(ptr+i) = i;
}
return ptr;
}
Upvotes: 1
Views: 40
Reputation: 2096
You've declared p
as an integer pointer. The function doOperation
takes an int reference as a parameter. doOperation(*p)
means that you're dereferencing the pointer (which points to the first element in the array) and passing it to the function. Also as @dxiv have pointed out, in the function getpointer
, the loop initializes 11 elements instead of 10. you can solve this by just changing <=
to <
.
If you want to pass the pointer by reference instead, the function doOperation
can look like this:
void doOperation(int *&ptr)
{
std::cout << "ptr:" << ptr << std::endl;
}
Then you can just pass the pointer as an argument like this:
doOperation(p);
Output:
p:0
ptr:0x2b71550
The code after the changes should look like this:
#include <iostream>
void doOperation(int *&ptr)
{
std::cout << "ptr:" << ptr << std::endl;
}
int *getpointer()
{
int *ptr = new int[10];
int i;
for (i=0; i < 10; i++)
{
*(ptr+i) = i;
}
return ptr;
}
int main()
{
int *p = getpointer();
std::cout << "p:" << *p << std::endl;
doOperation(p);
return 0;
}
Upvotes: 1