I am creating a function to split a char * into an array of other char * based on a target (which can be " ", "a", etc). In this example, I am using a white space (" ") to split my char * into an array of char *.
However, I am having some difficulties dealing with the dynamically allocated memory. I allocated memory for both the array of char * that I will be returning as the split function return value, and another one to copy each separated const * that I am reading from the main char * parameter.
#define MAX_SIZE 65535
#define MAX_SPLIT_SIZE 1023
char** a_split(char * x, const char * target, int sn){
char ** sa = nullptr;
size_t t_len = strnlen(target, MAX_SIZE);
if(t_len < 1 || t_len > MAX_SIZE){ return sa; }
int split_num = 0;
if(sn > 1 && sn < MAX_SPLIT_SIZE){
sa = new char * [sn + 1]();
split_num = sn;
}else if(sn == -1){
sa = new char * [MAX_SPLIT_SIZE + 1];
split_num = MAX_SPLIT_SIZE;
}else {
return sa;
}
char * ptr = x;
char * mi; // Match index.
int i = 0; // Index of 'sa' array.
while((mi = std::strstr(ptr, target)) && split_num--){
size_t dif = mi - ptr;
char * n_cstring = new char[dif + 1]();
memcpy(n_cstring, ptr, dif); // Copying content to new string.
sa[i++] = n_cstring; // Append new string to 'sa' array of split strings.
ptr += dif;
ptr += t_len;
delete [] n_cstring; // <------- This is causing some weird errors.
}
if(mi == nullptr){
sa[i] = ptr;
}
return sa;
}
int main(int argc, char * argv[]){
char c[] = "I love Thanos";
char ** x = a_split(c, " ", -1);
for(int i = 0; x[i]; i++){
puts(x[i]);
}
return 0;
}
I found out that when using 'delete [] n_cstring', instead of outputting the char *'s separately (like in "I" "love" "Thanos"), it is outputting "love" "love" "Thanos". It is making this kind of repetition for every example. Why is 'delete' doing this?
Also, as I am returning a dynamically allocated array ('sa'), where would you recommend me to delete it? - the main function does not recognize 'sa'.
std::vector<std::string>?constis an adjective.char* x = new... I read that asstd::string x;without the need for delete or the need to worry about its size