I'm attempting to write a method that splits a string up (according to a delimiter) into an array of strings, which returns at the end of the function. This problem gets a little hairy. Here's the current function:
char** splitString(char *c_str, int len, char delim)
{
char **temp;
char *str;
int i;
str = malloc(sizeof(c_str));
strcpy(str, c_str);
printf("%s\n", str);
temp = malloc(len*sizeof(char*));
temp[0] = malloc(MAXCHAR*sizeof(char));
temp[0] = strtok(str, &delim);
for(i = 1; i < len; i++)
{
temp = malloc(MAXCHAR*sizeof(char));
temp = strtok(NULL, &delim);
}
return temp;
}
The issue is as follows:
Say *stringX = "part1;part2;part3". You then have **splitup = splitString(stringX, 3, ';').
Well, originally, inside the function I used c_str directly with strtok() instead of copying it into str. temp would return as a perfectly split up string, but if you tried to use stringX after sending it through the function, it would be left with only "part1", and the rest would be gone.
So I tried using a temporary string (str), where stringX would not be affected, and that is the current state of the function. The initial strtok(str, &delim) returns "part1" fine, but the second call returns crazy characters, and the third call returns null. So while stringX is unaffected, temp doesn't return a very useful string.
How do I just make this thing return temp without going crazy on me?
char** splitString(char *c_str, int len, char delim)
{
char **temp;
char *str;
int i;
str = malloc(sizeof(c_str));
strcpy(str, c_str);
printf("%s\n", str);
temp = malloc(len*sizeof(char*));
temp[0] = malloc(MAXCHAR*sizeof(char));
temp[0] = strtok(str, &delim);
for(i = 1; i < len; i++)
{
temp = malloc(MAXCHAR*sizeof(char));
temp = strtok(NULL, &delim);
}
return temp;
}
The issue is as follows:
Say *stringX = "part1;part2;part3". You then have **splitup = splitString(stringX, 3, ';').
Well, originally, inside the function I used c_str directly with strtok() instead of copying it into str. temp would return as a perfectly split up string, but if you tried to use stringX after sending it through the function, it would be left with only "part1", and the rest would be gone.
So I tried using a temporary string (str), where stringX would not be affected, and that is the current state of the function. The initial strtok(str, &delim) returns "part1" fine, but the second call returns crazy characters, and the third call returns null. So while stringX is unaffected, temp doesn't return a very useful string.
How do I just make this thing return temp without going crazy on me?