views:

58

answers:

2

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!

+1  A: 
int* increment(int** i) { (**i)++; return *i;}

and

cout << *p2;
N 1.1
N 1.1
thanks but i need to return a reference in the function
Jonathan
@Code: reference to what? `*i` is also a reference to `**i`. Try to run the code with suggested changes and see if that is what you want.
N 1.1
+2  A: 

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 than int*.

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 of i. And since i is a pointer to a pointer to an int, in this line of code:

int* increment(int** i) { i++; return &i;}

you are returning the address of a pointer to a pointer to an int. That is why you are getting your error message cannot 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:

int& increment(int* i)

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:

(*i)++;

And then return the destination of the pointer as a reference:

return *i;

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:

int a=24;
int *p=&a;
int *p2;
p2 = increment(p);

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.

Smashery