Simple number generator process. Wont print array

Hi, I am working on a very large project and I made sample code with the problem I am trying to tackle.

If you have an arduino UNO you can run this code on your board and look through the serial monitor yourself. There are no other electronics associated with this code.

void FunctionA(int increment); 
int increment = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  increment++;
  FunctionA(increment);
}

void FunctionA(int increment) 
{
  int x = 0;
  int luckyArray[] = {};
  
  while (increment != 0) 
  {
    int luckyNum = random(2, 6);
    luckyArray[x] = luckyNum; 
    delay(1000);

    x++; 
    increment--;
  }

  int i = 0;
  while (x != 0) 
  {
    
    Serial.println(luckyArray[i]);
    i++;
    x--;
  }
  delay(1000);
}

Ok. The Serial monitor does not print out the array. Instead it prints out a bunch of outrageous numbers that have nothing to do with the number generating process. I tried using the iteration method

for (int i = 0; i < x; i++) 
{
    Serial.println(luckyArray[i]);
}

It still prints numbers that don’t make any sense.

Help will be appreciated, Thanks!

  • Joe
int luckyArray[] = {};

This statement is ill-formed. You created an array with 0 element which does not make sense.
To create an array in C/C++, you must either supply the element count:

int luckArray[2] = {};

or supply the elements:

int luckyArray[] = {0, 0};

Of course, you could also do both:

int luckyArray[5] = {10}; //the first element will be 10
                                      //the rest will be filled with 0

Thanks, This helped alot!