Skip to content
Marcos edited this page Oct 1, 2024 · 3 revisions

Función ft_memset

La función ft_memset llena un bloque de memoria con un valor específico durante un número determinado de bytes.

Explicación del comando man

MEMSET(3) (simplified)

NAME
    memset -- fill a byte string with a byte value
SYNOPSIS
    void *memset(void *b, int c, size_t len);
DESCRIPTION
    The memset() function writes len bytes of value c (converted to an unsigned char) to the string b.
RETURN VALUES
    The memset() function returns its first argument.

Explicación con mis palabras

La función memset() toma un bloque de memoria (apuntado por el argumento b), un valor (el argumento c), y una longitud len. Llena los primeros len bytes del bloque de memoria con el valor c (convertido a un unsigned char). La función devuelve el puntero al bloque de memoria original.

Implementación en C

Aquí te muestro mi implementación de la función ft_memset en mi proyecto de Libft.

Código de ft_memset

#include "libft.h"

void	*ft_memset(void *b, int c, size_t len)
{
	unsigned char	*tmp;

	tmp = (unsigned char *)b;
	while (len > 0)
	{
		*(tmp++) = (unsigned char)c;
		len--;
	}
	return (b);
}

Main para probar ft_memset

El siguiente código es un ejemplo de cómo puedes probar la función ft_memset():

#include <stdio.h>

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

int main(void)
{
	char str[50] = "Libft es genial!";
	
	printf("Antes de memset: %s\n", str);
	ft_memset(str, '*', 5);
	printf("Después de memset: %s\n", str); // Debe llenar los primeros 5 caracteres con '*'

	return 0;
}

Clone this wiki locally