ft_memcmp

one·2021년 1월 4일
0

✅memcmp

  • The memcmp() function compares the first n bytes (each interpreted as unsigned char) of the memory areas s1 and s2.
  • s1s2두 메모리를 n바이트 만큼 비교.

💾함수 원형

int memcmp(const void *s1, const void *s2, size_t n);

💻Parameters

  • s1, s2 : 비교할 메모리 블럭
  • n : 비교할 바이트 수

💻Return value

  • s1 == s2 : 0
  • s1 > s2 : 양수
  • s1 < s2 : 음수



💾함수 구현

#include "libft.h"

int	ft_memcmp(const void* s1, const void* s2, size_t n)
{
	unsigned char* a1;
	unsigned char* a2;
	size_t i;

	a1 = (unsigned char *)s1;
	a2 = (unsigned char *)s2;
	i = 0;
	while (i < n)
	{
		if (a1[i] != a2[i])
			return (a1[i] - a2[i]);
		i++;
	}
	return (0);
}

💾사용 예시

#include <stdio.h>

int main(void)
{
	char s1[] = "42cadet";
	char s2[] = "42cadetabc";
	printf("%d\n", ft_memcmp(s1, s2, 3));
	printf("%d\n", ft_memcmp(s1, s2, 8));

	return (0);
}

💡memcmpstrncmp

  • strncmps1s2 모두 Null이 나오면 카운트와 관계없이 종료.
  • memcmps1s2Null이 나오더라도 상관없이 n개까지 비교를 계속함.
  • 따라서 문자열을 비교 할 때에는 strncmp, 문자열이 아닌 경우에는 memcmp를 사용하여 비교.
profile
늘 호기심을 갖고, 새로운 것에 도전할 것.

0개의 댓글