Passing a pointer to a stack-allocated array: legal?

standby…

I messed up my original attempt to create a minimal example. The code shown here seems to work fine. (How do you delete a post, anyway?)

original note:

The following sketch is putting my electron into Hard Fault. I believe it comes from passing a stack-allocated array as an argument to f1(), but I don’t see why that should be a problem: we’re still lexically inside of f2(), so the array should still be on the stack.

(Note: I suspect the passing of the array to be the problem because in a larger sketch, the called function was getting an array of zeros. Paring it down to this minimal sketch resulted in Hard Fault errors.)

Is there anything obviously wrong with this?

SYSTEM_MODE(MANUAL)

#define N_VALUES 4

void f1(double values[]) {
  for (int i=0; i<N_VALUES; i++) {
    Serial.println(values[i]);
  }
}

void f2() {
  double x[N_VALUES];
  x[0] = 1.23;
  x[1] = 2.34;
  x[2] = 3.45;
  x[3] = 4.56;
  f1(x);
}

void setup() {
  Serial.begin();
}

void loop() {
  f2();
  delay(2500);
}

Solved. The real problem was trying to use the abs() function like this:

double err = abs(0.5 - samples[i])

which was always evaluating to zero. I forgot that it’s a macro.

1 Like

@rdpoor, just a note. It is always better to pass a pointer to an array than the entire array itself. This reduces the stack depth and makes the function call faster.

@peekay123: I’m sure you understand that I was passing a pointer – that wasn’t my question. But coming from a pure-C embedded code background, pointers are in my blood!! :slight_smile:

1 Like

@rdpoor, your right! I was reading too fast! DIV0 and out-bound indexes are just plain annoying :wink: