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);
}
The type
voidis incomplete type. You may not dereference a pointer of the typevoid *.From the C Standard (6.2.5 Types)
Within the function you just need to cast the pointer of the type
void *to the typeunsigned char *before using a loop.Pay attention to that the second parameter of the standard C function
memsetisint.Also used by you the type
unsigned intfor the objectithat plays the role of an index in general is wrong.The type
unsigned intcan be not large enough to store all values of the typesize_t. As a result you can get an infinite while loop.The function can be defined the following way