C - 在 memcpy 中使用 strchr

C - using strchr inside memcpy

我正在尝试制作一个简单的代码示例,其中我可以将一个子字符串转换为一个新字符串。

我的代码如下:

char titulo[20];
char line[] = "PRINCIPAL,1.Liga,2.Clubes,3.Jogadores,4.Relatorios,5.Sair;";
char *pos = strchr(line,',');

memcpy(titulo, line,*pos);

问题是,当我这样做时:

printf("%s",titulo);

我得到类似的东西:

PRINCIPAL,1.Liga,2.Clubes,3.Jogadores,4.Rela

因为您需要 null 终止 titulo。例子

char line[] = "PRINCIPAL,1.Liga,2.Clubes,3.Jogadores,4.Relatorios,5.Sair;";
char *pointer = strchr(line, ',');
if (pointer != NULL)
{
    char *substr;
    size_t length;
    length = pointer - line;
    /* Perhaps check if `length == 0', but it doesn't matter
     * because you would end up with an empty but valid sub string
     * anyway.
     */
    substr = malloc(length + 1);
    if (substr != NULL)
    {
        memcpy(substr, line, length);
        substr[length] = '[=10=]';
        /* Use `substr' here */
        printf("%s\n", substr);
        /* Don't forget to free */
        free(substr);
    }
}