Juan Bravo
Juan Bravo

Reputation: 33

Invalid initializer in struct function

I have a function Reference that returns a struct as shown below:

struct Reference_XS {
    float *mat_c;
};

struct Reference_XS Reference(
    float q0,
    float q1,
    float q2,
    float q3,
    float val1,
    float val2,
    float val3
)  
{
    float mat_a[3][3] = {
        (2*q0*q0)+(2*q1*q1)-1, (2*q1*q2)-(2*q0*q3), (2*q1*q3)+(2*q0*q1),
        (2*q1*q2)+(2*q0*q3), (2*q0*q0+(2*q2*q2)-1), (2*q2*q3)-(2*q0*q1),
        (2*q1*q3)-(2*q0*q2), (2*q2*q3)+(2*q0*q1), (2*q0*q0)+(2*q3*q3)-1
    };

    float mat_b[3][1] = { val1, val2, val3 };
    static float Mat_c[3];
    int i, k;
    float temp = 0;

    for (i = 0; i < 3; i++) {
        temp = 0;
        for (k = 0; k < 3; k++) {
            temp = mat_a[i][k] * mat_b[k][0] + temp;
            Mat_c[i] = temp;        
        }
    }

    struct Reference_XS data = { Mat_c };
    return data;
}

But in the main.c, when I called it like

struct Reference_XS Acc_G = Reference(
    q0_XS,
    q1_XS,
    q2_XS,
    q3_XS,
    acx_XS,
    acy_XS,
    acz_XS
);

It shows the error Invalid Initializer

Upvotes: 0

Views: 787

Answers (1)

chqrlie
chqrlie

Reputation: 145297

The most plausible explanation for this error is the struct Reference_XS Acc_G must be defined at the global scope. Initializers for global variables must be constant in C.

Upvotes: 2

Related Questions