Sofía Huppertz
Sofía Huppertz

Reputation: 21

What are the correct types for memset function?

On trying to recreate "memset" function I have error if I try to dereference a void pointer, or have a different type for the second argument than the first. To make the function work I had to change it to:

void ft_memset(unsigned char *st, unsigned char c, size_t n)

Is it possible to define the function as in the manual?

void *memset(void *s, int c, size_t n)  <- This is the man version.

I am doing it only with the library stdio.h to use size_t I have to compile wih -Wall -Wextra -Werror

This is my code:

#include <stdio.h>

//stdio.h to use size_t;
//

void *ft_memset(unsigned char *str, unsigned char c, size_t n)
{
    unsigned int i;

    i = 0;
    while (i < n)
    {
        str[i] = c;
        i++;
    }
    return(str);
}

Upvotes: 2

Views: 726

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

The type void is incomplete type. You may not dereference a pointer of the type void *.

From the C Standard (6.2.5 Types)

19 The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

Within the function you just need to cast the pointer of the type void * to the type unsigned char * before using a loop.

Pay attention to that the second parameter of the standard C function memset is int.

void *memset(void *s, int c, size_t n);

Also used by you the type unsigned int for the object i that plays the role of an index in general is wrong.

unsigned int i;

The type unsigned int can be not large enough to store all values of the type size_t. As a result you can get an infinite while loop.

The function can be defined the following way

void * memset( void *s, int c, size_t n )
{
    for ( unsigned char *p = s, ch = c; n != 0; n-- )
    {
        *p++ = ch;
    }

    return s;
}

Upvotes: 5

Related Questions