rpunet
rpunet

Reputation: 51

Do I need to typecast the void pointer again for the arithmetics after its been casted for the copy?

when doing that code:

void    *ft_memcpy(void *dest, const void *src, size_t n)
{
    void    *orgdest;

    orgdest = dest;
    while (n > 0)
    {
        *(unsigned char *)dest = *(unsigned char *)src;
        n--;
        dest++;
        src++;
    }
    return (orgdest);
}

the void pointer has been typecasted to unsigned char* to copy from src to dest. Then I use the pointers inside the while loop (dest++; src++;). Should I cast them again for the arithmetics (as they were void*, and cant be used for arithmetics) like dest = ((unsigned char *)dest + 1); or are they already casted to the unsigned char type and can be used?

Upvotes: 2

Views: 119

Answers (1)

Andrew Henle
Andrew Henle

Reputation: 1

Yes, you need to cast the pointers as arithmetic on void * pointers is illegal in C. Note that the increment is also not proper syntax, so you'd need to do

void    *ft_memcpy(void *dest, const void *src, size_t n)
{
    void    *orgdest;

    orgdest = dest;
    while (n > 0)
    {
        *(unsigned char *)dest = *(unsigned char *)src;
        n--;
        dest = ( unsigned char * ) dest + 1;
        src = ( unsigned char * ) src + 1;
    }
    return (orgdest);
}

Note that creating local copies of unsigned char * type is easier to understand:

void    *ft_memcpy(void *dest, const void *src, size_t n)
{
    const unsigned char *local_src = src;
    unsigned char *local_dest = dest;

    while (n > 0)
    {
        *local_dest = *local_src;
        n--;
        local_dest++;
        local_src++;
    }
    return (dest);
}

Upvotes: 2

Related Questions