Arduino IDE - C# - dynamic array?

Discussion in 'Programmer's Corner' started by Captain E, Jun 21, 2015.

  1. Captain E

    Thread Starter Member

    Jun 16, 2015
    I'm trying to make a dynamic array which I can add/remove and get values by their index.
    I havn't found any other way than using
    int myArray[8];​ make an array. But this way the array is not dynamic, it has a constant size.

    I tried using these two libraries:

    ..but none of them have any method for getting a value by index?
    StackArray got a "peek" method:

    T peek ()
    Get an item with data type "T" from the stack.
    ..but it has no parameters for the index.


    How do I create a dynamic array? (which I can get values by their index)

    Thank you in advance!
  2. Papabravo


    Feb 24, 2006
    What makes you think that the Arduino IDE supports C#? AFAIK what it supports is a derivative of C, that is not strictly C, but kind of like a bastard cousin.

    With a dynamic array you, or some agent, allocates a block of storage. Using a structure you overlay a template onto that storage and access elements by index and offset within the structure.
  3. Captain E

    Thread Starter Member

    Jun 16, 2015
    I see.. :D

    Guess I need to make a guess on how big it sometimes can get and set the size to that directly :|

  4. vpoko


    Jan 5, 2012
    Arduino uses the avr-gcc compiler which compiles a subset of C++ code, not C#. There is no support dynamically-sized arrays.

    While you can declare arrays that are always bigger than the biggest array you need, this is inefficient as you're wasting that memory whether or not you use it. Instead you should use malloc to allocate memory dynamically from the heap. How you organize it depends on how you want to use it, but one of the common data structures (e.g., queue, linked list, binary tree, minmax heap, etc.) will very likely serve your purpose.
    Papabravo likes this.
  5. Captain E

    Thread Starter Member

    Jun 16, 2015
    Oh okay, thanks :D
  6. sirch2

    Well-Known Member

    Jan 21, 2013
    AND there is no magic, things that look like "dynamic" arrays are just doing what vpoko suggests under-the-hood. I.e. they typically create a small-ish array (allocate some heap) and track the number of elements, when the array is full they allocate more space and add elements to that, and so on. You just need to roll your own.

    An Uno or similar 328 based Arduino has 2k of SRAM so you only have 2056 bytes of memory for program variables, so some care is needed with how that is used.