The idea of using pointers in this kind of situation is to allow you to pass a variable into a function. So you want 3 parameters, not 2 - something like void function2(double num1,double num2,double* result)
Since you say you'd rather work out the coding yourself, I won't give an implementation answer - but you will need to declare a double
variable outside the function (in main
), pass its address to the last argument (the address being a pointer), and then, in the function, change the value that the pointer points to to your result, using the dereference operator (*
). You don't need (or want) to return anything.
Pointers are tricky to understand. It doesn't help that they have to be introduced before the concepts that really require them, so the examples used often seem a bit contrived - if you were writing your function in a production program you'd probably just use the version that returns a value.
The idea is really to keep track of a single piece of memory, so you can use it in multiple places in your program. In this case, you are making a variable from outside a function accessible inside it so you can write to it.
As you probably know, when parameters are passed into C functions, they are copied into new memory inside the function. This is why changing the values of argument variables passed into a function inside it has no effect on the values of the variables outside. You can change them but it will have no effect because they are not the occupying the same memory. The pointer is a way of getting around this. It is just the address of some piece of memory, just a number. It doesn't matter that it gets copied when it is passed into the function, because we are not using it as a piece of memory, we are using the value it contains as a way of looking up the original variable memory from outside the function. So when you dereference the value of the pointer (using *) and assign to it, you will change the value of the variable outside the function, because that is the variable outside the function.
One advantage of doing things this way is that it frees up the return value of the function to do another job. Quite a few common C library functions use it this way e.g. sprintf
, fwrite
scanf
- usually to return the number of characters or bytes written, or to indicate failure.
The single most important use of pointers, however, is to deal with memory from the heap - i.e memory allocated by the programmer explicitly, using malloc
and similar functions. Once you start using malloc
, and understand how the heap works, pointers and the reasons for using them make a lot more sense, though it's still not always easy.