c++ - warning: address of local variable 'angles' returned [-Wreturn-local-addr] -


i'm trying return float x, y , z angle values body object ode (open dynamics engine) simulation.

float* creature::eulerangles(const float &q0, const float &q1, const float &q2, const float &q3){      float angles[3] = {atan2(2 * (q0*q1 + q2*q3), 1 - 2 * (q1*q1 + q2*q2)),                       asin( 2 * (q0*q2 - q3*q1)),                       atan2(2 * (q0*q3 + q1*q2), 1 - 2 * (q2*q2 + q3*q3))};     return angles; } 

because dbodygetquaternion returns 4 const float quaternions need rotations , i've had immense difficulty trying compile. compile i'm getting warning.

could explain me why , means please?

float angles[3] = { ... }; 

defines local array.

the statement

return angles; 

returns pointer first element of array.

however, array destructed function returns. hence, returned pointer dangling pointer.

that's compiler warning about. if dereference returned pointer in calling function, invoke undefined behavior.

in order return pointer array remain valid after function returns, need allocate dynamic memory , return dynamic memory.

float* creature::eulerangles(const float &q0, const float &q1,                              const float &q2, const float &q3) {    float* angles = new float[3];    angles[0] = atan2(2 * (q0*q1 + q2*q3), 1 - 2 * (q1*q1 + q2*q2));    angles[1] = asin( 2 * (q0*q2 - q3*q1));    angles[2] = atan2(2 * (q0*q3 + q1*q2), 1 - 2 * (q2*q2 + q3*q3));     return angles; } 

keep in mind if above, you'll have make sure call delete [] on returned pointer in calling function.

to avoid hassles of manually allocating , deallocating memory, can use std::vector<float> return type.

std::vector<float> creature::eulerangles(const float &q0, const float &q1,                                          const float &q2, const float &q3) {    std::vector<float> angles(3);    angles[0] = atan2(2 * (q0*q1 + q2*q3), 1 - 2 * (q1*q1 + q2*q2));    angles[1] = asin( 2 * (q0*q2 - q3*q1));    angles[2] = atan2(2 * (q0*q3 + q1*q2), 1 - 2 * (q2*q2 + q3*q3));     return angles; } 

with this, memory management done automatically you.

since size of array fixed @ 3, using std::array<float, 3> better using std::vectro<float>:

std::array<float, 3> creature::eulerangles(const float &q0, const float &q1, const float &q2, const float &q3) {    std::array<float, 3> angles;    angles[0] = atan2(2 * (q0*q1 + q2*q3), 1 - 2 * (q1*q1 + q2*q2));    angles[1] = asin( 2 * (q0*q2 - q3*q1));    angles[2] = atan2(2 * (q0*q3 + q1*q2), 1 - 2 * (q2*q2 + q3*q3));     return angles; } 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -