ft_memcmp

J_JEON·2021년 12월 22일
0

libft

목록 보기
12/44

💻 ft_memcmp

s1과 s2를 n만큼 비교하여 같은지 아닌지를 확인하는 함수

📃 ft_memcmp 원형

int	ft_memcmp(const void *s1, const void *s2, size_t n)

🔩 parameters

*s1 : 비교할 첫번째 메모리블록
*s2 : 비교할 두번째 메모리블록
n : 비교할 크기

📬 return

int형 반환

  • s1과 s2를 크기 n만큼 비교하여 모두 같다면 0을 반환
  • s1과 s2를 크기 n만큼 비교하던 중 다른부분이 나왔을때
    • 다른 부분이 나왔을때 s1이 더 크다면 양수를 반환
    • 다른 부분이 나왔을때 s2가 더 크다면 음수를 반환

🧨 주의사항

  • strncmp는 null이 나오게되면 비교를 종료하지만 memcmp는 null을 만나도 종료되지 않음

⌨ 코드


#include "libft.h"

int	ft_memcmp(const void *s1, const void *s2, size_t n)
{
	size_t	i;

	i = 0;
	while (i < n)
	{
		if (((unsigned char *)s1)[i] != ((unsigned char *)s2)[i])
		{
			if (((unsigned char *)s1)[i] > ((unsigned char *)s2)[i])
				return (1);
			return (-1);
		}
		i++;
	}
	return (0);
}
profile
늅늅

0개의 댓글