2d array changing untouched cells

im working on a school project and a boolean 2d array we are using is either not changing the spot in the array that we want to or its changing more then that cell, also the last number in the array is a random value between 0 and 255 even if its a bool

bool horWalls[7][8] =
{
  {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0}
};

byte cell[2];


void setup() {
  Serial.begin(9600);
  horWalls[ cell[1] + 2 ] [ cell[0] ] = 1;
  Serial.println("placehorwall"); 
}

void loop() {
for (int y = 0; y != 7 ; y++) {
      for (int x = 0; x != 7 ; x++) {
        Serial.print(horWalls[y][x]);
        Serial.print("  ");
      }
      Serial.println(horWalls[y][8]);
    }
    Serial.println("");
   }
    

results in
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 117 and the 117 changing even though its only serial prints
in a larger program neither of the 1's appear

this happens in a physical due and an online simulated mega in wokwi.com
is there a way to fix this?

In array of 8 elements there is no element with index 8. Therefore, your matrix doesn't contain the element

horWalls[y][8]);

Printing the non-existing element outputs the random value.

Also your for loops limits looks incorrect:

at least the limits of loops should be different because the array sizes in x and y dimensions are not equal.

also can you explain what's the formula is supposed to do (what is cell and why do you add 2 - could be out of bounds?)


Side note:

if you really have only 8 bools "horizontally" then you could reduce the memory 8x by using the bits of a byte to represent your state.

becomes

byte horWalls[7] ;

and you use the bitwise macros to access each pseudo "bool"

Bits and Bytes

bitClear()
bitRead()
bitSet()
bitWrite()

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