Hi
I am seeing an issue when populating an array with values.
Please see code below.
Under void setup()
I am populating an array with a For loop.
Then I print out the last value of the array
Under void loop()
If I read back the array with a For loop I get a strange value at the end of the array.
If I comment out the For loop it prints the correct last value of the array.
I would be grateful if anybody could point me to what I am missing here please? I have tried this on a Mega 2560 and an ESP32
Thank you in advance
Chazza
int myArray[255];
void setup() {
Serial.begin(115200);
for (int i = 0; i <= 255; i++) {
myArray[i] = i;
}
Serial.print("myArray[255] under setup = ");
Serial.println(myArray[255]);
} // end of setup
void loop() {
for (int i = 0; i <= 255; i++) {
Serial.print(i);
Serial.print(". ");
Serial.println(myArray[i]);
}
Serial.print("myArray[255] under loop = ");
Serial.println(myArray[255]);
while (1) {
}
}// end of loop
You are trying to fill 256 entries in a 255-entry array. Either change the array to "int myArray[256];" or change the loops so that the maximum index is 254, not 255.
Hi
Thank you all for the answers. I did suspect something along those lines but could not understand why Serial.print(myArray[255]) under setup yielded the right result but not when it was used under loop.
Also note that if you set the compiler warnings to "All" in the Arduino IDE's 'preferences' menu, then you'll see the following warning which would have tipped you off to a problem.
C:\arduino-1.8.15\portable\packages\arduino\hardware\avr\1.8.6\cores\arduino\main.cpp: In function 'main':
C:\Users\TR001221\AppData\Local\Temp\arduino_modified_sketch_379691\sketch_jan09a.ino:23:19: warning: iteration 255 invokes undefined behavior [-Waggressive-loop-optimizations]
Serial.println(myArray[i]);
^
C:\Users\TR001221\AppData\Local\Temp\arduino_modified_sketch_379691\sketch_jan09a.ino:20:21: note: within this loop
for (int i = 0; i <= 255; i++) {
^
C:\Users\TR001221\AppData\Local\Temp\arduino_modified_sketch_379691\sketch_jan09a.ino:7:16: warning: iteration 255 invokes undefined behavior [-Waggressive-loop-optimizations]
myArray[i] = i;
^
C:\Users\TR001221\AppData\Local\Temp\arduino_modified_sketch_379691\sketch_jan09a.ino:6:21: note: within this loop
for (int i = 0; i <= 255; i++) {
^