I'm using a customised C++ implementation of ArrayList based on the method found in Processing. The original code is by Obed Isai Rios, but I've added a version to Github with more explicit file structure. The arraylist is appended to by the add_string_item
method, which works ok in the format arraylist->add_string_item("text string")
but fails when the same input is a String variable. The following script illustrates:
#include "ArrayList.h"
void setup(){
ArrayList *list = new ArrayList("text1");
list->add_string_item("text2");
String str = "text3";
list->add_string_item(str);
}
void loop(){}
This fails on the last line with error message:
no matching function for call to 'ArrayList::add_string_item(String&)'
sketch_aug24b.ino: In function 'void setup()':
sketch_aug24b:7: error: no matching function for call to 'ArrayList::add_string_item(String&)'
/Users/robinedwards/Documents/Arduino/libraries/ArrayList/ArrayList.h:17: note: candidates are: void ArrayList::add_string_item(char*)
I'm not familiar with C++ so can't figure out why this method accepts a string but not when assigned to a String object str
. I'm pretty sure it's because I need to coerce to char* but not sure how to do this. I've tried toCharArray
without success, although this seems the right direction. Very grateful for any assistance.
ArrayList.cpp code:
#include "Arduino.h"
#include "ArrayList.h"
ArrayList::ArrayList(char* init){
stringlist = (char**)malloc(10*sizeof(char*));
stringlist[0] = init;
this->size = 1;
}
ArrayList::~ArrayList(void)
{
}
void ArrayList::add_string_item(char* item){
char **neulist = (char**)malloc((size+1)*sizeof(char*));
for(int i=0; i<size; i++){
neulist[i] = stringlist[i];
}
//
neulist[size] = item;
stringlist = neulist;
size = size + 1;
}
void ArrayList::set_string_item(char* item, int index){
stringlist[index] = item;
}
void ArrayList::remove_selected_item(int index){
char **neulist = (char**)malloc((size-1)*sizeof(char*));
//From Begining
for(int i=0; i<index; i++){
neulist[i] = stringlist[i];
}
//From next Index
for(int i=index; i<=size-1; i++){
neulist[i] = stringlist[i+1];
}
//free(matrix);
stringlist = neulist;
size = size - 1;
}
void ArrayList::empty_list(){
size = 1;
char **neulist = (char**)malloc((size)*sizeof(char*));
stringlist = neulist;
stringlist[0] = "EMPTY";
}
void ArrayList::display_string_list(){
Serial.begin(9600);
for(int i=0; i<size; i++){
Serial.println(stringlist[i]);
}
}
char** ArrayList::get_stringlist(){
return this->stringlist;
}
char* ArrayList::get_item(int index){
return this->stringlist[index];
}
void ArrayList::set_stringlist(char** stringlist){
this->stringlist = stringlist;
}
int ArrayList::get_size(){
return this->size;
}