Strange behavior storing objects on an array

Hi,
I created a class which basically stores info of events from a calendar. The private variables declaration looks like this:

	String _title;
	uint32_t _startTime, _endTime;
	short int _timezone;

And the basic constructor (although I use another one which parses a string)

CalendarEvent::CalendarEvent() {
	_title.reserve(50);
	_title = "";
	_startTime = 0;
	_endTime = 0;
	_timezone = 0;
}

So in order to store them, I decided to go for a private array of 5 CalendarEvents, and 2 public functions to add an item to the array and to get it by index:

static CalendarEvent eventList[5];
...

void CalendarEvent::addEvent(CalendarEvent& event){
	if(_eventPtr < 5){
		memcpy(&eventList[_eventPtr++], &event, sizeof(event));
	} else {
		_eventPtr = 0;
		memcpy(&eventList[_eventPtr++], &event, sizeof(event));
	}
}

CalendarEvent CalendarEvent::getEvent(uint8_t index){
	if(index < 5){
		CalendarEvent event = CalendarEvent::eventList[index]; //Note I only do this redundancy for debugging purposes
		return event;
	} else return CalendarEvent();
}

And this is how I create and add the item in main.cpp:

CalendarEvent event = CalendarEvent(dataStr);
CalendarEvent::addEvent(event);

Now if I retrieve data from event in main, I get all the fields correctly; but if I access the stored objects via CalendarEvent::getEvent(index), I can perfectly obtain the _startDate and _endDate, but the String _title is gibberish, not even alphanumeric values.
any clues on what could be happening?

cheers

String _title;

String does not contain the actual bytes of the string, but instead contains a pointer to a string in the heap. Copying the struct or object containing the string does not copy the string content, which, I guess, is probably overwritten by the time you go fetch it.

I understand. Before trying memcpy I tried variable by variable assignment to no avail either, but I don't remember the exact problem. I'm going to try again and see the result.
Thanks!

Ps: Got it working :slight_smile:

void CalendarEvent::addEvent(CalendarEvent& event){
	if(_eventPtr < 5){
		eventList[_eventPtr++] = event;
	} else {
		_eventPtr = 0;
		eventList[_eventPtr++] = event;
	}
}

thanks again ^^

Learn to use c char array strings and the string.h functions when working in small memory environments.
C++ String Objects are waste-y and hog cycles. Buffered-strings and pointers are definite and direct.
You know pointers?

Classes are okay but dynamic allocation in AVR-tight memory is asking for trouble. Set up buffers and work with those through pointers. Allocate once rather than repeated allocate-deallocate and your loop() will run a bit faster.

Actually, I'm working on a Due so I've got RAM enough. But yes, I should switch to c strings at some point, probably once I get everything working this way

The problem is that it isn't working that way.