W4lker
W4lker

Reputation: 51

Using pointers as function parameters

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?

Upvotes: 0

Views: 127

Answers (2)

David G
David G

Reputation: 96810

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;
}

Upvotes: 3

Mats Petersson
Mats Petersson

Reputation: 129374

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; 

Upvotes: 1

Related Questions