Duplicate a StackArray from a pointer ?

Hi,

I am using the StackArray library to save a action history in it.

When I want to display this history, I don’t want to remove items from it, so if I use pop() method on my history, I am going to lose them.

I was thinking of making a copy of my StackArray and use pop() on that copy to read items, so I don’t loose the original. But I have a problem to duplicate my StackArray from a pointer, it seem that calling pop() on that copy is crashing the code.

Here is the resumed code :

void Display::DrawHistoryScreen(StackArray<float>* history)
{
  ...

  StackArray<float> historyCopy = *history;

  for (int i=20; i<64; i=i+8)
  {
    if (!historyCopy.isEmpty())
    {
      float hour = historyCopy.pop();
      
      ....
      }
    }
  }
}

This work correctly if I use the original history (history->pop() because of the pointer) but crash with the copy.

Thank for your help.

I was thinking of making a copy of my StackArray and use pop() on that copy to read items

Bad idea. Much better would be to add a method to the StackArray class to show the data.

But I have a problem to duplicate my StackArray from a pointer,

Or maybe with how you call the function. Having two pointer that point to the same data is going to cause problems when you pop all the data. It is going to disappear from the one StackArray that both pointers point to.

  StackArray<float> historyCopy = *history;

That is NOT making a copy.

If you REALLY must do this useless copy, simply pop all the data off one stack, print it, push it onto another stack, and then reverse the process when the original is empty (without printing on the second pop/push pass).

PaulS:
Bad idea. Much better would be to add a method to the StackArray class to show the data.

You are probably right. I added a method to the StackArray library, not sure if it will work fine, I am not at home at the moment and I don’t know if there is a way to debug on an Arduino.

// get item at index
T getItem (int index);

// get item at index
template<typename T>
T StackArray<T>::getItem (int index) {
  // check if the stack is empty.
  if (isEmpty ())
    exit ("STACK: can't get item from stack: stack is empty.");

  if (index > size-1)
	  exit ("STACK: can't get item from stack: index out of stack.");

  // fetch the top item from the array.
  T item = contents[index];

  // return the top item from the array.
  return item;
}

I do not like that method. I’d prefer to see the signature be:

template<typename T>
bool StackArray<T>::getItem (int index, T &val)

That way, you can return true or false (there was, or was not) a value at that index and the value (if index is valid) at that index.

I do not like having library methods crash my Arduino because I called a function to get a value that was not in the expected range.

But, as long as you make sure to call the function correctly, it should work.