Home > other >  Why is my code with chars messing up a counting variable?
Why is my code with chars messing up a counting variable?

Time:06-04

This is Arduino code, but I have a feeling my error is with C in general and not specific to Arduino. I'm new to pointers and strings, so I probably am doing something wrong in that regard.

This is from a much larger program, but I've whittled it down to as little code as I can where I can still reproduce the bug.

It should just iterate through the letters of text[] and save each letter into newText[0][0], as well as print newText[0][0] and the counter variable i.

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

void loop() {
  const char text[] = "chunk";
  static char newText[][10] = {};

  static unsigned int i=0;
  static int code = 0;     

  if(code == 0){
    
      newText[0][0] = text[i]; //This
      Serial.print(i);
      Serial.println(newText[0][0]); //This
      
      i  ;
      
      if(i>=strlen(text)){
        code=1;
      }
  }
}

But as I have the code, i jumps to some number like 104 by the second iteration, when it should be equal to 1. (The exact value varies depending on how exactly the code looks.) If I comment out either of the lines that have the comment //This, then the counter works fine. Also, if I switch Serial.print(i); and the line before it, then it counts fine.

CodePudding user response:

static char newText[][10] = {};

This creates a zero sized array (to be more precise a matrix of 0 rows and 10 columns). This would be illegal in C but gcc has an extension to allow it. Nevertheless even with gcc's extension, it's UB when you access newText[0][0] which is outside the size of the array. When you have UB anything can happen, the program can appear to work as you expect, it can print gibberish, it can crash, etc., literally anything.

So you need to declare a size that accommodates all your accesses, e.g.:

static char newText[1][10] = {};

if you only want 1 row (but in this case you don't need a matrix, a one dimension array would do fine).


Tip: use the String class for strings instead of raw arrays.

  • Related