Dynamic array

Hey people,

What I'm trying to do is to read input from the Serial port on Arduino Mega2560 and store it in an array whenever there is data. The array will be used as soon as it's populated and then when there is more data available on the serial comms, it can be reused.

The problem is the size of the array, which is not known since it's the same as the size of the data on the serial com.

if(Serial.available())
  {
    SerialAvailable = Serial.available();
    Serial.write(SerialAvailable);
    Serial.println();
    uint8_t payload[SerialAvailable];
    while(SerialAvailable > 0)
    {
      payload[counter] = Serial.read();
      Serial.write(payload[counter]);
      counter++;
      SerialAvailable--;
      
      
    }

This code doesn't give any errors at compiling, but when the I run it with a for-loop to print the elements of the array, I get random stuff every time I send something over the serial. And they're not consistent, so the data could be "123" and the printed data is something random, and then the second time I send "123" and I get something completely different than the first one.

Any suggestions on how to do this would be much appreciated.

You have to use a fixed size array. Pick a size that will handle 99% of the expected data. Only store that amount of data in the array, discarding the rest.

If you provided some info about the source of the data, there might be other ways to deal with the data without having to buffer (so much of) it.

PaulS:
You have to use a fixed size array. Pick a size that will handle 99% of the expected data. Only store that amount of data in the array, discarding the rest.

If you provided some info about the source of the data, there might be other ways to deal with the data without having to buffer (so much of) it.

Right now it's nothing too huge, I'm just trying to get this to work; but eventually, the Arduino is supposed to read data off a sensor (based on what the sensor is being told to return the response is anything between 8 to 32 bits), pass it to xbee to be sent to a central point (using API) and stored on the computer.