C: creating array of strings from delimited source string

前端 未结 5 1547
野的像风
野的像风 2020-12-10 07:52

What would be an efficient way of converting a delimited string into an array of strings in C (not C++)? For example, I might have:

char *input = \"valgrind         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 08:31

    What's about something like:

    char* string = "valgrind --leak-check=yes --track-origins=yes ./a.out";
    char** args = (char**)malloc(MAX_ARGS*sizeof(char*));
    memset(args, 0, sizeof(char*)*MAX_ARGS);
    
    char* curToken = strtok(string, " \t");
    
    for (int i = 0; curToken != NULL; ++i)
    {
      args[i] = strdup(curToken);
      curToken = strtok(NULL, " \t");
    }
    

提交回复
热议问题