For loop does confusing mistakes

Hello, first time poster here.

I have a confusing behavior of my For Loop. he makes mistakes.

The output should be

1 2 3 4…69 70 71 72 100 101 …128 129 0 I shortet it a little bit but I think you know what I mean.

The result in the serial monitor is

1 2 3 4 … 69 70 71 72 100 101 … 112 113 114 12659 14645 0 118 25975 0 121 122 123 124 125 126 127 128 129 0

When i use the function with 50 new numbers it goes on correct after 121 like in the example.

I tried to slow down the loop but it didnt work. Also i testet it on a nano and uno with no dupont attached.

Please help me.

The code is part of a bigger project but i shortet it down and tested standalone.

int m = 71;
int i,f;

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

}

void loop() {
  
  int a[] = {           1,  2,  3,  4,  5,  6,  7,  8,
                    10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
                    20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
                    30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
                    40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
                    50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
                    60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
                    70, 71, 72, 0
             };
             

  Erweiterung ( a, 100, 20);
  
  Darstellung(a);
}

void Erweiterung ( int a[], int v, int l){ // v=Startnummer der Erweiterung l=Anzahl der Plättchen

  for (i = m; i < m + l; i++)
  {
    a[i] = v;
    delay (20);
    v = v + 1;
    delay (20);
  }
  a[m + l] = 0;
  m = m + l;
}

void Darstellung ( int a[]){
  
   for (f = 0; f <= m; f++)
  {
    Serial.print(a[f]);
    Serial.print(" ");
    delay (20);
  }
  Serial.println();
  exit(0);
  }

Welcome

By setting m to 71, l to 20, then doing

for (i = m; i < m + l; i++)
{
  a[i] = v;

You are writing outside the bounds of a…

And similarly, when doing :

m = m + l;
...
for (f = 0; f <= m; f++)
{
  Serial.print(a[f]);

You are reading outside the bounds of a

1 2 3 4…69 70 71 72 100 101 …128 129 0 I shortet it a little bit but I think you know what I mean.

No, it’s not clear at all, why should it jump from 72 to 100 and then back to 0 after 129 ?

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