스닥 2020. 8. 10. 13:33

헤더 파일

<string.h>

사용 목적

두개의 메모리 주소값을 지정한 길이 만큼 비교

프로토타입과 매개변수

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

1. const void *s1 = 비교할 메모리 A

2. const void *s2 = 비교할 메모리 B

3. size_t n = 비교할 길이(byte 단위)

 

반환값

1. 비교하는 동안 두 메모리가 완벽하게 일치하면 '0'을 반환

2. 두 메모리가 일치하지 않은 지점이 있으면 *s1 - *s2를 반환

함수의 원리

이해를 돕기 위해 같은 동작을 하는 함수를 만든 것입니다.

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

	i = 0;
	while (i < n) // 지정한 n 길이만큼 메모리를 하나씩 비교
	{
		if (*(char *)s1 != *(char *)s2) // 메모리의 값이 다르면
			return (*(unsigned char *)s1 - *(unsigned char *)s2); 
            // 그 메모리의 값의 차를 반환 (*s1 - *s2)
		i++;
		s1++;
		s2++;
	}
	return (0);
}

사용 예시

#include <string.h>
#include <stdio.h>

int		main(void)
{
		char s1[] = "Life Is Fortytwo";
		char s2[] = "Life is Fortytwo"; // 대문자 I와 소문자 i의 차이가 있음

		printf("Return Value is = %d\n", memcmp(s1, s2, 20));
		return(0);
}
Return Value is = -32