C 언어에서 memcmp()와 memicmp()는 두 개의 메모리 블록에 대해 앞에서부터 n바이트를 비교하는 함수입니다. 두 함수는 이름이 비슷하지만 동작 방식에서 중요한 차이점을 가지고 있습니다.
memcmp와 memicmp의 주요 차이점
- memcmp()는 문자를 부호 없는 문자(unsigned char)로 취급하여 비교하며, 대소문자를 엄격하게 구분합니다.
- memicmp()는 문자로 비교하되 대문자와 소문자를 구분하지 않고 비교합니다(ignore case).
- 두 함수 모두 정수형 값을 반환합니다.
반환값의 의미
- 두 메모리 버퍼가 같으면 0을 반환합니다.
- 첫 번째 버퍼가 두 번째 버퍼보다 크면 0보다 큰 값을 반환합니다.
- 첫 번째 버퍼가 두 번째 버퍼보다 작으면 0보다 작은 값을 반환합니다.
예제 프로그램
다음 프로그램은 memcmp()와 memicmp() 함수의 실제 사용법을 보여줍니다.
#include<conio.h>
#include<mem.h>
main(){
char st1[]="This is C Programming language";
char st2[]="this is c programming";
int result;
result=memcmp(st1,st2,strlen(st2));
printf("\n1. result after comparing buffer using memcmp");
check(result);
result=memicmp(st1,st2,strlen(st2));
printf("\n2. result after comparing buffer using memicmp");
check(result);
}
check(int x){
if(x==0)
printf(" buffer st1 and st2 hold same data\n");
if(x>0)
printf("buffer st1 is bigger than buffer st2\n");
if(x<0)
printf(" buffer st1 is less than buffer st2\n");
}실행 결과
위 프로그램을 실행하면 다음과 같은 결과를 확인할 수 있습니다.
1. result after comparing buffer using memcmp buffer st1 is less than buffer st2 2. result after comparing buffer using memicmp buffer st1 and st2 hold same data
결과 분석
memcmp()는 대소문자를 구분하기 때문에 'T'와 't'를 서로 다른 문자로 판단합니다. 아스키 코드상 소문자가 대문자보다 값이 크므로, st1의 'T'(84)가 st2의 't'(116)보다 작아 첫 번째 버퍼가 더 작다고 출력됩니다. 반면 memicmp()는 대소문자를 무시하고 비교하기 때문에 두 버퍼의 데이터가 같다고 판단하여 0을 반환한 것입니다.