A few month ago i made a function (thanks to the help of the forum) that take a char string and split it into a 2D array of char strings.
Now i would like to make this function without the need to continually call for malloc/realloc/free but using a pre-fixed buffer
//g++ 5.4.0
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdint.h>
#define print std::cout
#define endl "\n"
char **stringSplit(char ***dest_arr, size_t *len_dest_arr, constchar *str, constchar *delimiters)
{
int str_len = strlen(str) + 1; // add null terminator
char str_copy[str_len]; // we work on a copy
strcpy(str_copy, str);
bool allocate = false;
if (*dest_arr == nullptr)
{
allocate = true;
}
if (allocate)
{
*dest_arr = (char **)malloc(sizeof(char *) * str_len); // over size
}
uint8_t counter = 0; // limited to 255 sub strings
char *token = strtok(str_copy, delimiters); // split until first delimiter
while (token != nullptr)
{
if (allocate)
{
(*dest_arr)[counter] = (char *)malloc(sizeof(char) * (strlen(token) + 1)); // add null terminator
}
strcpy((*dest_arr)[counter], token); // copy token to dest_array
token = strtok(NULL, delimiters); // continue splitting
counter++;
}
if (allocate)
{
*dest_arr = (char **)realloc(*dest_arr, sizeof(char *) * counter); // reallocate the right amount of memory
}
*len_dest_arr = counter; // save size
return (*dest_arr);
}
int main()
{
char log[] = "this is a test";
char buffer[60][10];
size_t buffer_len;
stringSplit(&buffer, &buffer_len, log, " ");
}
but then, how could i call the function? because the above code would give me conversion errors, I tried almost everything this morning but I am not able to make it working
Also really even if i am using the arduino framework to be more precise i am on the esp8266/esp32 which actually implemented the STL inside the core, so i guess i could use them
However just being memory safe doesn't mean the program won't crash. For example what is the significance of that magic number 3? What happens if words contains 3 or less elements?