I'm working on a project and I'd like to populate an array on setup instead of in the main loop but I can't seem to get it to work and I'm not sure why. Below is the very basic example of my code. You can see that I have a call for a function in the setup but when printed out my array is nothing but zeros. If I call that same function in the main loop it works as expected.
uint8_t myArray[10][3];
void setup() {
Serial.begin(115200);
// put your setup code here, to run once:
Fill();
}
void loop() {
// put your main code here, to run repeatedly:
//Fill();
Serial.print(myArray[0][0]);
Serial.print(", ");
Serial.print(myArray[0][1]);
Serial.print(", ");
Serial.println(myArray[0][2]);
}
void Fill(){
for (int i; i < 3; i++){
myArray[0][i] = i;
}
}
Turn up the level of warnings in preferences.
You'll get some complaints from the compiler about this:
for (int i; i < 3; i++){
Better:
for (int i=0; i < 3; i++){
Ok... I guess I'm a little confused on why this works lol. By setting i equal to zero fixed the issue. Care to explain?
Thanks for the solution by the way.
If you don't set it to zero then what will its initial value be ?
As it is a local variable it could be anything (unlike a global which would be set to zero). If its initial value is 3 or more then the for loop will not run and the values in the array will be left at zero from when when it was declared as a global variable
I'm sure this is a good habit to get used to but I'm confused on why not setting i to 0 in the mail loop assumes as such but not in the setup. I will be sure to get in the habit no matter what though.