0

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

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
Bassusour
  • 175
  • 6
  • 14
  • 1
    Your initializer elements are not constant expressions. – Martin James Aug 18 '17 at 19:48
  • 1
    The initializer for a `static` object must be a *constant expression*, meaning something that can be evaluated at compile time (a literal, a macro that expands to a literal, or an expression containing only those elements). The values of `x`, `y`, and `z` are not established until run time, so they cannot be used as initializers for a `static` array. – John Bode Aug 18 '17 at 19:51

1 Answers1

2

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97