看看其他答案,对于 C 语言的初学者来说,由于代码的大小,它看起来很复杂,我想我会把它放在初学者身上,实际解析字符串而不是使用strtok
...像这样的东西:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char **parseInput(const char *str, int *nLen);
void resizeptr(char ***, int nLen);
int main(int argc, char **argv){
int maxLen = 0;
诠释 i = 0;
字符 **ptr = NULL;
char *str = "valgrind --leak-check=yes --track-origins=yes ./a.out";
ptr = parseInput(str, &maxLen);
if (!ptr) printf("错误!\n");
别的{
for (i = 0; i < maxLen; i++) printf("%s\n", ptr[i]);
}
对于 (i = 0; i < maxLen; i++) 自由(ptr[i]);
免费(ptr);
返回0;
}
char **parseInput(const char *str, int *Index){
字符 **pStr = NULL;
字符 *ptr = (char *)str;
int charPos = 0, indx = 0;
而 (ptr++ && *ptr){
if (!isspace(*ptr) && *ptr) charPos++;
别的{
调整大小 (&ptr, ++indx);
pStr[indx-1] = (char *)malloc(((charPos+1) * sizeof(char))+1);
如果 (!pStr[indx-1]) 返回 NULL;
strncpy(pStr[indx-1], ptr - (charPos+1), charPos+1);
pStr[indx-1][charPos+1]='\0';
字符位置 = 0;
}
}
如果(字符位置> 0){
resizeptr(&pStr, ++indx);
pStr[indx-1] = (char *)malloc(((charPos+1) * sizeof(char))+1);
如果 (!pStr[indx-1]) 返回 NULL;
strncpy(pStr[indx-1], ptr - (charPos+1), charPos+1);
pStr[indx-1][charPos+1]='\0';
}
*索引=索引;
返回 (char **)pStr;
}
void resizeptr(char ***ptr, int nLen){
if (*(ptr) == (char **)NULL){
*(ptr) = (char **)malloc(nLen * sizeof(char*));
if (!*(ptr)) perror("error!");
}别的{
char **tmp = (char **)realloc(*(ptr),nLen);
if (!tmp) perror("错误!");
*(ptr) = tmp;
}
}
我稍微修改了代码以使其更容易。我使用的唯一字符串函数是strncpy
..确保它有点冗长,但它确实动态重新分配字符串数组而不是使用硬编码的 MAX_ARGS,这意味着双指针在只有 3 时已经占用了内存或 4 会做,这也将使内存使用效率和微小,通过 using realloc
,简单的解析被employing 覆盖isspace
,因为它使用指针进行迭代。当遇到空格时,它会realloc
吃掉双指针和malloc
保存字符串的偏移量。
请注意函数中如何使用三重指针resizeptr
。事实上,我认为这将成为一个简单 C 程序、指针、realloc、malloc、按引用传递、解析字符串的基本元素的一个很好的例子......
希望这会有所帮助,最好的问候,汤姆。