0

I want to do a function that uses pointers a s parameters and return one of the pointers, is it possible?

Example:

int* sum(int* x, int* y, int* total){
    total=x+y;
    return total;
}

I get this error:

main.cpp:10:13: error: invalid operands of types 'int*' and 'int*' to binary 'operator+'

How can I do that using only pointers and not references?

4
  • 2
    Try *total = *x + *y (and as a side note, both the x and y pointers should be const, or in-fact not even pointers in this example). Commented Sep 5, 2013 at 16:35
  • en.wikipedia.org/wiki/Dereferencing Commented Sep 5, 2013 at 16:36
  • 2
    I almost fainted when I see this. Commented Sep 5, 2013 at 16:36
  • 3
    @texasbruce: Everyone starts somewhere Commented Sep 5, 2013 at 16:38

2 Answers 2

3

You need to dereference the pointers to return a reference to the object they point to:

*total = *x + *y;

However, in C++ you can use references to facilitate this:

int sum(int x, int y, int& total)
{
    total = x + y;
    return total;
}

The reference is only declared with total because that is the only argument we need to change. Here's an example of how you would go about calling it:

int a = 5, b = 5;
int total;

sum(a, b, total);

Now that I think of it, since we're using references to change the value, there really isn't a need to return. Just take out the return statement and change the return type to void:

void sum(int x, int y, int& total)
{
    total = x + y;
}

Or you can go the other way around and return the addition without using references:

int sum(int x, int y)
{
    return x + y;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming this worked (it doesn't compile, rightly so):

 total=x+y;

it would give you the pointer that points at the address of x + the address of y. Since this is [nearly] always nonsense, the compiler doesn't allow you to add two pointers together.

What you really want is to add the value that int *x and int *y POINTS AT, and store it in the place that total points at:

*total = *x + *y; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.