Pointers

The following code compiles runs, and usually gives the expected result but it contains a serious flaw. What is this flaw? Why is the program still able to produce the expected result? How can I rewrite both the function, and the calling code, so that the program no longer contains the flaw.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
 using namespace std;

 double* average ( double val1 , double val2)
 {
 double ave = (val1 + val2)/2;
 return &ave;
 }

 int main ()
 {
 double* ave = 0;
 ave = average (2, 3.1);
 cout << "The average is " << *ave << endl ;
 }
For some reason you are returning to the variable which is destroyed after function execution.
One solution is to make it return by value instead of pointer.
Second is to dynamically alllocate memory
Third to return pointer to the static variable
Okay thanks I'll try it out
Could you please elaborate more
Double isn't big enough in size to justify passing back a pointer. Just pass back by value.

EDIT: ... or do you not fully understand the difference between passing by value and/or pointer?
Last edited on
I don't think I do. Could you please explain
1
2
3
4
5
double* average ( double val1 , double val2)
{
double ave = (val1 + val2)/2;
return &ave; //Returning address to the local varuable
} //ave is destroyer here and any attempt to use returned value is undefined behavior 
Correct and most desireable way:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

double average (double val1 , double val2)
{
    double ave = (val1 + val2)/2;
    return ave;
}

int main ()
{
    double ave = average (2, 3.1);
    std::cout << "The average is " << ave << std::endl ;
}
I recommend you to read this: http://www.cplusplus.com/doc/tutorial/pointers/
Last edited on
Does it matter where you put the asteriks (*)?
Yes.
Does that change it from a dereference operator to a pointer?
About the code. Currently it's a function returning a pointer to a double. Am I correct?
Your code is function returning invalid pointer to double. I described, why, previously.
The original post is returning the address of a local double variable, that is then deleted once the function returns (and this, as has been said results in undefined behavior).
Last edited on
How does the swap function work?
From what I understand it just swaps the two pointers around.
When you use the function swap(&x, &y), what does this do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include <iostream>

using namespace std;

void swap (int * x_ptr , int * y_ptr )
{
int* temp = x_ptr ;
x_ptr = y_ptr ;
y_ptr = temp ;
}
int main ()
{
int x = 7;
int y = 12;
swap (&x ,&y);
cout << "x: " << x << endl ;
cout << "y: " << y << endl ;
return 0;
}
Last edited on
You should be assigning the values that pointers are pointing to.

1
2
3
int temp = *x_ptr ;
*x_ptr = *y_ptr ;
*y_ptr = temp ;
Last edited on
Topic archived. No new replies allowed.