Bassusour
Bassusour

Reputation: 175

"initializer element is not constant" and "near initialization"

I want to return an array, and since it doesn't matter if it gets overwritten, my method is this:

double * kryds(double linje_1[], double linje_2[]){
double x = linje_1[1]*linje_2[2]-linje_1[2]*linje_2[1];
double y = linje_1[2]*linje_2[0]-linje_1[0]*linje_2[2];
double z = linje_1[0]*linje_2[1]-linje_1[1]*linje_2[0];
static double svar[] = {x, y, z};
return svar;
}

However, I get an error at the static double svar[] = {x, y, z}; . Can someone please explain what it means? I've read other forum posts like this one but that doesn't really apply to my case

Upvotes: 0

Views: 851

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

First of all, it means what it says

  • Initializers must be constant expressions,

but not just that you can't return a local array because it's undefined behavior (making it static solves the problem but causes other problems), instead try with a struct.

struct point3d {double x; double y; double z; };
struct point3d kryds(double *linje_1, double *linje_2)
{
    struct point3d result;
    result.x = linje1[1] * linje2[2] - ...
    result.y = ...

    // and so on
    return result;
}

Or if you MUST return a double *, then try with malloc() which is better than static double svar[]

double *svar;

svar = malloc(3 * sizeof(*svar));
if (svar == NULL) // This will almost NEVER happen, but you MUST check
    return NULL;
svar[0] = linje_1[1] * linje_2[2] - linje_1[2] * linje_2[1];
// And so on

you need to remember to free() the pointer later on when you know for sure that you wont use it anymore.

Or, if you insist

static double svar[3];

svar[0] = linje_1[1] * linje_2[2] - linje_1[2] * linje_2[1];
// And so on

and you don't need auxiliary x, y and z in any of the proposed solutions in my answer.

Upvotes: 2

Related Questions