Getting gibberish when writing to an array

Hey guys,

I'm trying to write a script that writes -1 to all values in an array except the last, which will be filled with 1. The serial monitor shows that it does this. However, the actual size of the array is double the expected size of the array and the values in the extra half of the array are all gibberish to me.

Here is the code I am using

void setup() {
  Serial.begin(9600);
}
void loop() {
    int a_rows = 5;  //size of array
    int test[a_rows]; //initialize array
    for (int i = 0; i <a_rows ; i++) {
      if (i<a_rows-1) {
          test[i] = -1;
      }
      else if (i==a_rows-1) {
        test[i] = 1;
        break;
      }
    }
    Serial.println("size: ");
    Serial.println(sizeof(test));
    Serial.println();
    for (int k=0;k < sizeof(test); k++) {
     Serial.println(test[k]);
}
     Serial.println();
       delay(2000);
}

I have attached an image of the output.

The problem might stem from how I initialize the array, but I cant quite put my finger on what.
I'm fairly new to c++ so I'm probably missing something.

Any help in resolving this issue is appreciated. Thanks in advance.

output.png

sizeof() give the size of the array in bytes. An int is 2 bytes x 5 elements = 10 bytes, thus the size result is correct. The reason the last 5 values read from the array are gibberish is because you're reading past the end of the array and getting whatever happens to be in memory at those locations.

The correct way to calculate the number of elements in an array is this:

sizeof(test)/sizeof(test[0])

That will work no matter what type you use.