我正在尝试解析一些包含一些文件名作为参数的字符串 . 我的目标是 parse 命令及其参数和 store 它到2d char数组 .

示例输入:

/* Where 'cmd' is a command, file* are the arguments */
cmd file1 file2 file3

这是我的代码:

int8_t **file_names = NULL;

/* Allocate Memory for the array,  
Max of 5 files of max strlen 64 each */
file_names = malloc(sizeof(char *));
for(i=0; i<5; i++)
*(file_names + i) = malloc(sizeof(char) * 64);

/* Receive command from user */
cmd = malloc(sizeof(char) * 1024);
printf("Please Enter the command:\n");
fgets(cmd, 2048, stdin);
cmd[strlen(cmd) - 1] = '\0';   /* Overwrite Newline by '\0' char */

int j = 0;
/* Tokenise the file names and cpy to 2d array */
ptr = strtok(cmd, " ");        /* Contains command 'cmd' */
printf("First Token  : [%s]\n\n", ptr);

printf("Parsing Filenames now:\n");
while(ptr = (strtok(NULL, " ")))
{
    printf("\tToken  : [%s]\n", ptr));
    memcpy(*(file_names + j), ptr, strlen(ptr));        /* Copy to 2D array */
    printf("\tFile Name : [%s]\n", *(file_names + j));
    j++;
};

输出是:

$ gcc 2d.c -Wall -Wextra
$ ./a.out 
Please Enter the command
cmd file1 file2 file3
First Token  : [cmd]

Parsing Filenames now
    Token  : [file1]
    File Name : [file1�,    ȡ,  �,  X�, ��, ]
    Token  : [file2]
    File Name : [file2]
    Token  : [file3]
    File Name : [file3]

Issue

我不知道为什么第一个令牌附加了垃圾 . 而 ptr 获取正确的数据 . 我怀疑 memcpy ,但 strlenptr 返回正确的 5 字节 .

strtok(3)还说:每次调用strtok()都会返回一个指向包含下一个标记的以null结尾的字符串的指针 .

所以我认为它应该以null结尾并且只应打印 file1 .