I want to write a function that splits a string given by the user on the command-line by the first occurrence of a comma and put in an array.
This is what I've tried doing:
char**split_comma(const str *s) {
char *s_copy = s;
char *comma = strchr(s_copy, ",");
char **array[2];
*(array[0]) = strtok(s_copy, comma);
*(array[1]) = strtok(NULL,comma);
return array;
}
This is the main function:
int main(int argc, char **argv) {
char **r = split_comma(argv[1]);
printf("substring 1: %s, substring 2: %s\n", r[0],r[1]);
return 0;
}
Can someone please give me some insight as to why this doesn't work?
This is working.
You need to allocate enough space for the 2 destination char buffers
first
andsecond
.Here's a simple solution where we first duplicate the input string
s
, then find the comma and replace it with a string terminator character (0). The first string then is at the beginning of s , and the second string is after the 0: