7sain
7sain

Reputation: 1

What is ((unsigned char *)b)[i] = c; mean in c?

void    *ft_memset(void *b, int c, size_t len)
{
    size_t i;

    i = 0;
    while (i < len)
    {
        ((unsigned char *)b)[i] = c;
        i++;
    }
    return (b);
}

Upvotes: 0

Views: 374

Answers (2)

Pointers to void

Pointer to object of any type can be implicitly converted to pointer to void (optionally const or volatile-qualified), and vice versa.

Pointers to void are used to pass objects of unknown type, which is common in generic interfaces.

When it comes to your question, it is releveant what your function does. As the name suggests, the parameter b points to a block of memory of size len (bytes), which has to be filled with a specific value, described by c.

In order to set each byte of the block of memory, we have to be able to access each byte individually. We achieve that by casting the pointer to an unsigned char, the 'byte' type in C.

  • cast generic pointer to a pointer to type unsigned char:
    ((unsigned char *)b)

  • access the ith element in that array:
    [i]

Equivalent to:

unsigned char *bytes = (unsigned char*) b;
for (size_t i=0; i < len; ++i)
    bytes[i] = c;

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311118

You could write for example

b[i] = c;

However the dereferencing the pointer of the type void *

void *b

yields an object of the incomplete type void. So the compiler will issue an error.

So at first the pointer of the type void * is cast to the pointer type unsigned char * and then the subscript operator is applied

((unsigned char *)b)[i] = c;

Now as the type unsigned char is a complete type the compiler can use the pointer arithmetic in the evaluation of the subscript operator.

Pay attention to that the subscript operator is evaluated like

*( ( unsigned char * )p + i ) = c;

Upvotes: 2

Related Questions