'C++ Pointers and Functions with no return - need to recall the output as a pointer
Write a C++ code that calls the function add_three() that takes three float numbers and add them together, the function should not return anything, and the output variable should be passed as an input to the function. Note: the number of argument is four.
#include <iostream>
using namespace std;
void add_three(float, float *);
int main()
{
float s,r;
float a[3];
add_three(a[3], &r); //use of undeclared identifier 'a'
cout<< "The sum is " << s; //use of undeclared identifier 's'
return 0;
}
void add_three(float a[3], float *s)
{
float r = 0;
for(int i=0; i<3; i++)
{
cin >> a[i];
r = r + a[i]; //invalid operands to binary expression ('float *' and 'float')
}
*s = &r;
}
Errors:
assigning to 'float' from incompatible type 'float *'; remove &
*s = &r;
I am stuck and can't understand what I am doing wrong (BTW, I am a complete novice).
Solution 1:[1]
The first problem is that you attempt to pass a single float value to the function, which is declared to take a single float value.
Then you create an overload of that function, which takes a pointer to a float value. The function declaration
void add_three(float, float*);
is different from
void add_three(float*, float*);
You also make it worse by passing the fourth element from your three-element array.
Then there's the assignment
*s = &r;
It tries to assign the pointer to the variable r (the type of the expression &r is float*) to the floating-point value *s.
You probably want
*s = r;
Or better yet, use proper references to pass s by reference:
// First argument: Pass a pointer to the first element of the array
// Second argument: Pass a reference to the variable
void add_three(float* a, float& s);
Call as:
float a[3];
float s;
add_three(a, s);
As an alternative you could return the sum instead of passing references. This is actually the method I recommend:
// First argument: Pointer to the first element of your array
// Returns: The sum of all three elements
float add_three(float* a);
Call as:
float a[3];
float s = add_three(a);
Or considering that you don't actually use a in the main function, you could skip passing it as an argument. In fact, you don't need an array at all:
float add_three()
{
float input, sum = 0; // Initialize sum to zero
for (unsigned i = 0; i < 3; ++i)
{
// Note: Really need some error checking and validation here
std::cin >> input;
sum += input;
}
return sum;
}
Simply call as:
float s = add_three();
Even if you must use arguments to "return" the value, you can do it without the array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
