Can you create an array in the main loop?

I'm trying to learn about arrays. From what I know i usually you have to declare the array name and size alongside the included libraries and global variables. I've noticed that the size of the array can't just be an integer, it has to be a constant integer.
My problem is that i want to store data in an array, but the length of the array will be different each time and found only during the main loop.
Is there a way to create an array with a variable length during the main loop. or do i just create a big enough array to cover all possibilities, and then just fill the rest of the array with zero's during the main loop?

No.

The array can be created with each loop iteration with a different size using a variable.

voiding loopy()
{
int MyArraySize = SomeSourceOfANumber;
int myarray [MyArraySize];
}

I prefer to create an array larger then needed and just keep track of how many array cells are in use per loop iteration. It takes time to create and destroy an array.

1 Like

i often define arrays (of struct) with a max size along with a count of the # of elements it contains. that count is incremented with each new value added, up to the max. for example

#define MaxClient    10
Node nodes [MaxClient] = {
    { N_INIT, "192.168.0.41" },
};
int nNodes = 1;

C/C++ has a malloc() that support dynamically allocating space. this is fine on a PC but for smaller processors such as an Arduino, RAM is limited and it's usually better to pre-allocate the the space that discover at run time there's not enough RAM for such things as well as stack variables

1 Like

This is technically correct : C++ standard (till C++11) doesn’t support variable sized arrays. The C++11 standard does mentions array size as a constant-expression.

But... actually Variable-length automatic arrays are allowed in ISO C99 or C11 ( flexible arrays), and as an extension GCC accepts them in C90 mode and in C++

As we use GCC, and knowing it's not standard C++, you could have a local array and change its length at each loop

you can try this

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

void loop() {
  Serial.println("Enter array size: ");
  // not a clean way but for demonstration sake
  while (Serial.available() == 0) yield(); // wait for user input
  long size = Serial.parseInt();
  while (Serial.available() != 0) Serial.read(); // empty the rest of the buffer

  Serial.print("creating an array with "); Serial.print(size); Serial.println(" entries. (no error checking!)");

  byte dynamicArray[size];

  for (int i = 0; i < size; i++) dynamicArray[i] = random(i);

  Serial.write('[');
  for (int i = 0; i < size; i++) {
    Serial.print(dynamicArray[i]); Serial.write(' ');
  }
  Serial.println("]");

}

the array is allocated on the Stack, so stack size restrictions may apply on some platforms

2 Likes

Congratulations, you've asked a question for which the answer is really "it depends".

What processor? An Uno? Don't consider it; zero memory garbage collection means every redefinition/reallocation may result in out-of-memory, and there's no 'system' on an Uno to advise you, it just crashes. ESP32? Probably not going to be a problem. Hence, you really need to give more context to get an authoritative answer.

1 Like

dynamic size array? that's what std::vector is for
https://en.cppreference.com/w/cpp/container/vector#Example

1 Like

yeah but does not work on UNO

2 Likes

so? did OP specify it must be for UNO? it works on esp8266 for example.

1 Like

Sure

My point was that it does not work by default everywhere in arduino land, so if you offer that idea (containers is indeed the right approach in C++), don’t forget to mention the limitations.

2 Likes

And beyond.

1 Like

Nah, I would rather encourage to upgrade to better hardware instead. Not wasting time dealing with "worse" hardware, being in the 21. century.

Time costs more than hardware. And actually, "better" hardware might be even cheaper :wink:

1 Like

Indeed it was once discussed for c++14 and did not make it and probably won’t happen

Some good links on VLA here

1 Like

That’s a different discussion so I won’t hijack that thread

Remember OP is just at the stage of learning and is trying to play with arrays. That should be the main focus of this discussion (even if I feel it’s OK to mention alternatives)

1 Like

That might be appropriate, if we even knew what hardware he's using. But...
@batterylicker how about sharing some info, there's more than enough OT conjecture floating around here. Participation on this forum really is a two-way street, we help you if you play along.

2 Likes

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