The main problem is that you're returning the address of the local variable named ret
which is created on the stack and which will go out of scope once you return from that function. That is, you should not return the address of a local non-static object from a function.
Solution 1
One way would be to create the variable ret
on the heap using new
as shown below:
#include <iostream>
struct Mystruct { int a, b; };
Mystruct *sum_struct(const Mystruct *x, const Mystruct *y)
{
Mystruct *ret= new Mystruct(); //note the use of keyword new here. Also note that ret is a pointer now
ret->a = x->a + y->a; //note the use of ret->a instead of ret.a since ret is a pointer now
ret->b = x->b + y->b; //note the use of ret->a instead of ret.a since ret is a pointer now
std::cout << ret->a << "--" << ret->b << "--\n"; // Shows 6--7--
return ret;
}
int main()
{
Mystruct o, p, *q;
p.a = 1; p.b = 2;
o.a = 5; o.b = 5;
q = sum_struct(&o, &p);
std::cout << q->a << "--" << q->b << "--\n"; // shows 6--7--
//use delete
delete q;
}
The output of the above program can be seen here. Note that instead of manually managing memory using new
/delete
, it would be better to use smart pointers.
Solution 2
Here instead of returning a pointer we just return a Mystruct
object by value.
#include <iostream>
struct Mystruct { int a, b; };
//the function return a Mystruct object by value
Mystruct sum_struct(const Mystruct *x, const Mystruct *y)
{
Mystruct ret{0,0};
ret.a = x->a + y->a;
ret.b = x->b + y->b;
std::cout << ret.a << "--" << ret.b << "--\n"; //Shows 6--7--
return ret; //return ret by value
}
int main()
{
Mystruct o, p, q; //note q is not a pointer now
p.a = 1; p.b = 2;
o.a = 5; o.b = 5;
q = sum_struct(&o, &p);
std::cout << q.a << "--" << q.b << "--\n"; // shows 6--7--
}
The output of the above program can be seen here
Solution 3
You can use std::unique_ptr
as shown below:
#include <iostream>
#include <memory>
struct Mystruct { int a, b;
};
std::unique_ptr<Mystruct> sum_struct(const Mystruct *x, const Mystruct *y)
{
std::unique_ptr<Mystruct> ret(new Mystruct()); //since std::make_unique() does not exist in C++11.
//std::unique_ptr<Mystruct> ret= std::make_unique<Mystruct>(); //with C++14
ret->a = x->a + y->a;
ret->b = x->b + y->b;
std::cout << ret->a << "--" << ret->b << "--\n"; //Shows 6--7--
return ret;
}
int main()
{
Mystruct o, p;
p.a = 1; p.b = 2;
o.a = 5; o.b = 5;
std::unique_ptr<Mystruct> q = sum_struct(&o, &p);
std::cout << q->a << "--" << q->b << "--\n"; // shows 6--7--
//no need to use delete
}
Note that with C++14 you can use std::unique_ptr<Mystruct> ret= std::make_unique<Mystruct>();
instead of using std::unique_ptr<Mystruct> ret(new Mystruct());
since std::make_unique
isn't available in C++11.