Append text to char array

Hey all, I started using the arduino back in November. Electronics in general for that matter. So this physical computing thing is pretty new to me. I really can’t believe its already been 4 months since then.

I am working on a little Thingy®©? that will let me set some text and have it marquee across an 8x8 matrix. What I don’t know how to do in all of this is add the text to a char array. I thought I got close with:

//Tried to post link to source but it won't let me on my first post


 C++ Syntax (Toggle Plain Text)

      // First allocation
      T *p = new T[N];
       
      // Resize by creating a new array
      T *save = new T[N * 2];

      // Copy the data
      for ( int i = 0; i < N; i++ )
      save[i] = p[i];

      // Change the size to match
      N *= 2;

      // Destroy the old array
      delete [] p;

      // Reset to the new array
      p = save;

But alas it does not seem that you can delete in the arduino code base. Nor did the array = diffArray; work for me either.

So I ask the world…f?þ?ø?`ó æ ? ø ?þ?ø? æ?ø?þ. Sorry wrong baud rate…How would you add a char to the end of a char array that has already been declared?

Thanks world.

You can use malloc and free to allocate and free dynamic memory as in the following:

      T *p = malloc(sizeof(T) * N);

      // Resize by creating a new array
      T *save = malloc(sizeof(T) * N * 2);

      // Copy the data
      for ( int i = 0; i < N; i++ )
      save[i] = p[i];

      // Change the size to match
      N *= 2;

      // Destroy the old array
      free(p);

      // Reset to the new array
      p = save;

While dynamic memory allocation is the way to go on other platforms (Windows, Mac, UNIX) I personally would never use this in code for small microcontrollers. Some of the issues are as follows:

  • When using malloc/free you add code overhead (your sketch will grow) as the memory management fuctions will have to be linked with your code.
  • When allocating memory, you reserve more RAM than you actually need because memory management needs to allocate/maintain a reference table of allocated blocks and sizes.
  • Memory fragmentation may render a large part of your RAM unaccessible (your code above is a perfect example of this being the case)
  • Due to the limited RAM available you’re likely tu run out of RAM very quickly and this will lead to errors that are very hard to debug and control.

So what’s the solution then?

If you need dynamic storage, you can declare local storage in a function/subroutine. This temporary storage will be released when you exit the function with no danger of memory fragmentation.

If you need dynamic storage that must be globally accessible, you can declare this storage globally with the maximum size you will ever need. This is then a predictable well know limitation that you can code against.