I am trying to write a function that takes a pointer argument, modifies what the pointer points to, and then returns the destination of the pointer as a reference.
I am getting the following error: cannot convert int*** to int* in return
Code:
#include <iostream>
using namespace std;
int* increment(int** i) {
i++;
return &i;
}
int main() {
int a=24;
int *p=&a;
int *p2;
p2=increment(&p);
cout<<p2;
}
Thanks for helping!
If you indeed mean “return the destination of the pointer as a reference”, then I think the return type you’re after is
int&rather thanint*.This can be one of the confusing things about C++, since
&and*have different meanings depending on where you use them.&is “Reference type” if you’re talking about a variable definition or return type; but it means “Address of” if it’s in front of a variable being used after it’s defined.I could be completely mistaken, but it seems to me that you’ve gotten these two meanings mixed up; and since you want to return a reference, you’ve written “
return &i“, since&is used for references. However, in this case, it returns the address ofi. And sinceiis a pointer to a pointer to an int, in this line of code:you are returning the address of a pointer to a pointer to an
int. That is why you are getting your error messagecannot convert int***' to int*.Let’s walk through your code line by line. You are after a program that takes a pointer and returns a reference. So that would be:
We don’t need the double pointer that you had in your code (unless you want a pointer to a pointer). Then you want it to modify what the pointer points to:
And then return the destination of the pointer as a reference:
Here, we are dereferencing
i. Remember that using references lets you treat them like normal variables, and handles the pointer stuff for you. So C++ will figure out that you want it to be a reference.Then, to use your code, you can do pretty much what you had, but using less pointers:
I haven’t tested any of this, so anyone may feel free to edit my answer and fix it if I’ve got something wrong.