Wrote its split function (As, for example, in Java or Python):

  char **split(char *str, char *tok, int *len) { char **out = new char*[1]; (*len) = 0; char *token = strtok(str, tok); while (token != nullptr) { out[(*len)++] = token; char **copy = new char*[(*len) + 1]; for (int i = 0; i < (*len); i++) copy[i] = out[i]; delete[] out; out = copy; token = strtok(0, tok); } return out; } int main() { int len = 0; char **dataBase = split("asdasd asd asdasdasd asdasd asdasd asdadsasd asd", " ", &len); return 0; } 

However, it does not work - error code 139, because of the string char *token = strtok(str, tok); (checked in debager). Question: what am I doing wrong?

  • Is this a problem, or is it necessary to solve a real problem? Why not use boost::split ? - Alex Titov

2 answers 2

I do not know what "error code 139" is, but it immediately catches my eye that as the first argument you pass a string that cannot be changed. Attempting to call the strtok() for it, the code will obviously crash into something like the Segmentation fault .

PS Well, yes, so cycling in C ++ is the point?

    You do not want - since you have C ++ - get vector<string> ? This is much more logical, no memory leaks, no problems with the release later ...

    Correcting your code is difficult, because you get entangled in it in an array of pointers and do something completely different - you need to rewrite it. But if this is C ++ (moreover, C ++ 11, as you yourself write), it is easier to do so if you really want to get an array of strings:

     vector<string> split(const char *str, const char *tok) { vector<string> res; string s(str); for(char *token = strtok(s.data(),tok); token;token = strtok(nullptr,tok)) { res.emplace_back(token); } return res; }