Search code examples
cstringsubstringmemcpystrchr

C - using strchr inside memcpy


I am trying to make a simple code sample, in which I can have a sub-string, into a new string.

My code is below:

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

memcpy(titulo, line,*pos);

The problem, is that when I do:

printf("%s",titulo);

I get something like:

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


Solution

  • Because you need to null terminate titulo. Example

    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] = '\0';
            /* Use `substr' here */
            printf("%s\n", substr);
            /* Don't forget to free */
            free(substr);
        }
    }