Search code examples
arraysscopearduino-c++

How to set size of a global array from within if statement


I'm writing this code for Arduino. When compiling, I get the error "'timing' is not declared in this scope" (in the line near the bottom where I'm trying to print timing[i]) because I declared the array inside an if statement inside a while loop, I suppose.

If this were a simple variable, I could just declare it outside of the loop and this would be fixed, but the problem is that I only know the size of this array once in the if statement.

void loop() {

  while (Serial.available()) {
    int inChar = Serial.read();

    if (isDigit(inChar)) {
      inString += (char)inChar;
    }

    if (!isDigit(inChar) && !timingExists) {
      int timing[inString.toInt()];
      inString = "";
      timingExists = true;
    }

    if (!isDigit(inChar) && timingExists) {
      timing[n] = inString.toInt();
      inString = "";
      n++;
    }

  }
  n = 0;
  for (int i = 0; i < (sizeof(timing) / sizeof(timing[0])) ; i++) {
    Serial.println(timing[i]);
  }

}

Solution

  • What about using dynamically allocated memory? Declare a pointer to an int, outside the if scope.

    int * timing = NULL;
    

    And when you know the size of the array dynamically allocate memory using new.

    timing = new int[NUMBER];
    

    Where NUMBER is the number of elements you want to store in the array.

    Of course, remember to delete the allocated memory when you are done.

    delete [] timing;