这将是一个分隔的字符串转换为字符串在C(不是C ++)阵列的有效途径?例如,我可能有:
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 --leak-check=yes --track-origins=yes ./a.out"源字符串永远只有一个空格作为分隔符。我想malloc分配的字符串数组malloc分配的char * myArray的[] 这样:
myarray[0]=="valgrind" myarray[1]=="--leak-check=yes" ...修改我要假设有在 inputString ,所以我不能只是将其限制在10令牌任意数量或一些东西。
Edit I have to assume that there are an arbitrary number of tokens in the inputString so I can't just limit it to 10 or something.
我已经尝试与 strtok的凌乱的解决方案,并链表我已经实现,但抱怨Valgrind的这么多,我就放弃了。
I've attempted a messy solution with strtok and a linked list I've implemented, but valgrind complained so much that I gave up.
(如果你想知道,这是一个基本的Unix shell我试着写。)
(If you're wondering, this is for a basic Unix shell I'm trying to write.)
推荐答案什么是关于这样的:
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"); }更多推荐
C:从分隔源字符串创建字符串数组
发布评论