Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

Splitting a string at a delimiter and storing substrings in char **array in C

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
", r[0],r[1]);
   return 0;
}

Can someone please give me some insight as to why this doesn't work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to allocate enough space for the 2 destination char buffers first and second.

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:

/* Caller must call free() on first */
void split_comma( char* s, char** first, char** second )
{
    char* comma;
    if(!s||!first||!second) return ;
    *first = strdup(s) ;
    comma=strchr(*first,',') ;
    if(comma) {
        *comma = 0 ;
        *second = comma + 1 ;
    } else *second = 0 ;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...