different array values returned from function

Hello,
sorry if there is error in my language.

I want to know what is the problem with my code

const int LDR1 = A0;
const int LDR2 = A2;
const char SEPARATOR[] = ", \t";


void plotSignal(int n, int s[]) {
  int i;
  for (i = 0; i < n - 1; i++) {
    Serial.print(s[i]);
    Serial.print(SEPARATOR);
  }
  Serial.println(s[i]);
}

void ldrInit() {
  pinMode(LDR1, INPUT);
  pinMode(LDR2, INPUT);
}


int *ldrRead() {
  int data[3];
  data[0] = analogRead(LDR1);
  data[1] = analogRead(LDR2);
  data[2] = millis() / 1000;
  plotSignal(3, data);
  return data;
}
unsigned long last_millis = 0;

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

void loop() {
  if (millis() - last_millis > 1000) {
    int *data = ldrRead();
    data[3] = 180;
    plotSignal(3, data);
    last_millis = millis();
  }
}

So i want to read data from LDR sensor and print it in serial monitor. The problem is the value from void loop is different from what is initially read from inside the function. I am expecting the two data has the same value at least for the first two element in the array.

The schematics is in Schematics.jpg if you need it
and what I got from the output is in Monitor.png

thanks in advance

p.s. I am using Arduino Nano with old bootloader

Don't return a pointer to a stack object.

You could make the

  int data[3];
  static int data[3];

The

  int data[3];

in the function causes the compiler to put the values on the stack

When you return from the function, values previously held on the stack are pulled off so that the state of the program is restored to how it was when the function was called and hence the value of locally declared variables are lost

Of you declare the data array as static, as suggested, it will prevent the value being put on the stack and being lost. You could achieve the same thing by declaring the data array as global and thus removing the need to return it

I also see

    data[3] = 180;

in the program. Does the data array actually have an element numbered 3 ?

Works like a charm
Thanks for the answer. I am struggling with pointers, memory, and things like that in C.

btw the

data[2] =180

doesn't have any meaning it just to differentiate the two outputs

i think it was some residue from the bigger code to control a servo motor

data[2] =180

would not be a problem as long as that is what you meant to do
However

data[3] =180

could be if the data array only has 3 elements

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.