Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return float array from a function c++

Tags:

c++

arrays

What am I doing wrong?

In the first print the values are fain, in the second it's all zeros.

The first print - q: 0.965926 0.000000 0.258819 0.000000

The Second print - q: 0.000000 0.000000 0.000000 0.000000

float *AnglesToQaternion(float roll, float pitch, float yaw) { // Convert Euler angles in degrees to quaternions

    static float q[4];

    roll  = roll  * DEG_TO_RAD;
    pitch = pitch * DEG_TO_RAD;
    yaw   = yaw   * DEG_TO_RAD;

    float t0 = cosf(yaw * 0.5);
    float t1 = sinf(yaw * 0.5);
    float t2 = cosf(roll * 0.5);
    float t3 = sinf(roll * 0.5);
    float t4 = cosf(pitch * 0.5);
    float t5 = sinf(pitch * 0.5);

    q[0] = t0 * t2 * t4 + t1 * t3 * t5;
    q[1] = t0 * t3 * t4 - t1 * t2 * t5;
    q[2] = t0 * t2 * t5 + t1 * t3 * t4;
    q[3] = t1 * t2 * t4 - t0 * t3 * t5;

    printf(">> q-1: %f %f %f %f \n", q[0], q[1], q[2], q[3]);

    return q;
}

float q[4] = *AnglesToQaternion(0, 30.0, 0); 
printf(">> q-2: %f %f %f %f \n", q[0], q[1], q[2], q[3]);
like image 811
Gal Dalali Avatar asked Dec 11 '22 05:12

Gal Dalali


1 Answers

Don't return an array at all.

using degree = float;

struct Angles {
    degree roll;
    degree pitch;
    degree yaw;
};

struct Quaternion {
    float i;
    float j;
    float k;
    float l;
};

Quaternion angles_to_quaternion(Angles angles) 
{ 
    float yaw = angles.yaw * DEG_TO_RAD;
    float pitch = angles.pitch * DEG_TO_RAD;
    float roll = angles.roll * DEG_TO_RAD;

    float t0 = cosf(yaw * 0.5);
    float t1 = sinf(yaw * 0.5);
    float t2 = cosf(roll * 0.5);
    float t3 = sinf(roll * 0.5);
    float t4 = cosf(pitch * 0.5);
    float t5 = sinf(pitch * 0.5);

    return {
        t0 * t2 * t4 + t1 * t3 * t5,
        t0 * t3 * t4 - t1 * t2 * t5,
        t0 * t2 * t5 + t1 * t3 * t4,
        t1 * t2 * t4 - t0 * t3 * t5,
    };
}
like image 177
Caleth Avatar answered Jan 07 '23 21:01

Caleth