简体   繁体   中英

Pointer function confusion C++

I'm working my way through Jumping into C++ and I just reached the sections on pointers and consequently, my first wall. I'm trying to solve this problem:

Problem 13.4

Write a function that takes two input arguments and provides two separate results to the caller, one that is the result of multiplying the two arguments, the other the result of adding them. Since you can directly return only one value from a function, you'll need the second value to be returned through a pointer or reference parameter.

I just don't understand the question really. I need to write a function, for example:

int function(int x, int y){
    int addition = x + y;
    int multi = x * y;
}

But I since I don't fully understand the question I don't know how to fit in pointers. If anyone can dumb it down for me I would be grateful.

Thanks for your time!

You can try

  int functionPtr(int x, int y, int* addition) {
    // As JustSid mentioned in the comment, it would be good to check the pointer first
    if (addition) {
      *addition = x + y;
    }
    return x * y;
  }

Or

  int functionRef(int x, int y, int& addition){
    addition = x + y;
    return x * y;
  }

And when you want to call them

int x = 1;
int y = 2;
int addition1 = 0;
int multi = functionPtr(x, y, &addition1);

int addition2 = 0;
int multi = functionRef(x, y, addition2);

It means that the caller supplies room for the other result.
Example:

int function(int x, int y, int& res2)
{
  res2=x+y;
  return x*y;
}

A bit off topic because I don't really like the question Problem 13.4 poses... you can return an entire object if you wanted. Consider:

class AddMul {
public:
    int added;
    int multiplied;
};

AddMul function(int x, int y) {
    AddMul am;
    am.added = x + y;
    am.multiplied = x * y;
    return am;
}

Of course then you could consider some other interesting things, like maybe the AddMul class contains the function as a member? Or maybe it's the constructor directly?

class AddMul {
public:
    int added;
    int multiplied;

public:
    AddMul(int x, int y) {
        added = x + y;
        multiplied = x * y;
    }

    int getAdd() const {
        return added;
    }

    int getMul() const {
        return multiplied;
    }
};

Anyway, something to consider.

This is not what the book is asking you to do, but it is worth knowing the alternative to supplying pointers / references to return more than one result from a function.

std::pair<int, int> function(int x, int y)
{
    std::pair<int, int> p;
    p.first = x + y;
    p.second = x * y;
    return p;
}

I'm super rusty at C++ so forgive me if I'm a bit off in my answer, but basically pointers are variables that give the ADDRESS OF some data, rather than the data itself. This means that you can pass the address of an integer into a function to allow that function to then follow the pointer and store data in that integer's memory location. To get the address of a variable or object, you use the ampersand (&) and to follow a pointer you use the asterisk (*)

Example:

int main(void){
  int x = 2;
  int y = 3;
  int multiplicationResult = 0;
  int additionResult = twoOperations(x, y, &multiplicationResult); // The ampersand allows us to pass in a pointer to the memory address of multiplicationResult, rather than the value currently stored in it (0)
  // additionResult will now be 5
  // multiplicationResult will now be 6 - our function was able to store the result in memory using the pointer so we didn't need to use an assigment statement.
}

int twoOperations(int x, int y, int *multiResult){
  int addition = x + y;
  *multiResult = x * y; // The asterisk basically means "follow this pointer and store the result in that memory location."
  return addition;
}

When reading code to myself I first learned how to deal with pointers by reading the symbols aloud to myself like this: * = "Follow the pointer to..." & = "The memory address of..."

Hope this helps!

This is the important part of the text:

Write a function that takes two input arguments and provides two separate results to the caller[...]

Which means the caller of sumAndProduct can call it to receive both sum and product, this fictional syntax should convey the meaning:

int main() {
    int sum;
    int product

    (sum, product) = sumAndProduct(29, 541);

    printf("the sum of the two numbers is %d and the product is %d\n", sum, product);
}

However, no such syntax in C exists. The exercise asks you to find a way to do it with existing C syntax (hint: the function parameters' types can be int* or int& .)

EDIT: you can have a function that takes 4 arguments, where two out of those are input arguments and two are output arguments; thus having a 4-arg function that takes exactly two input arguments.

Since the problem says 'function that takes two input arguments', you cannot have 3 parameters in the function. One way to achieve this is to return a pointer to an array. So

int * function(int x, int y) {
    int * res = new int[2];
    //Perform computation
    //res[0] = ...
    //res[1] = ...
    return res;
}

Note that you should deallocate the array memory in the calling function.

int function(int a, int &b){
   if (a == 0 || b == 0)
   {
     int bb = b;
     b = 0;
     return a+bb;
   }         
   b = (b*a);      
  return a+(b/a);
}

this may be bad, it does however only have 2 parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM