Hàm memcmp so sánh n byte của 2 vùng nhớ

int memcmp(const void *buf1, const void *buf2, size_t count);

Parameter:

buf1: vùng nhớ cần so sánh

buf2: vùng nhớ cần so sánh

count: số byte cần so sánh

Remark:

Hàm memcmp( ) so sánh count byte của buf1 và buf2. Hàm trả về:

>0 : nếu buf1 “nhỏ hơn” buf2

<0 : nếu buf1 “lớn hơn” buf2

=0 : nếu buf1 “ bằng” buf2

Ví dụ:

#include "stdio.h"
#include "conio.h"
#include "string.h"

void main( void )
{
    int int_arr1[] = {1, 2, 3, 4};
    int int_arr2[] = {1, 2, 3, 5};
    int res;

    res = memcmp(int_arr1, int_arr2, 1*sizeof(int));
    if(res == 0)
        printf("\narr1 is equal to arr2");
    else if(res > 0)
        printf("\narr1 is greater than arr2");
    else
        printf("\narr1 is less than arr2");

    res = memcmp(int_arr1, int_arr2, 4*sizeof(int));
    if(res == 0)
        printf("\narr1 is equal to arr2");
    else if(res > 0)
        printf("\narr1 is greater than arr2");
    else
        printf("\narr1 is less than arr2");
    getch();
}

Kết quả:

Hàm memcmp so sánh n byte của 2 vùng nhớ
Hàm memcmp so sánh n byte của 2 vùng nhớ

Be the first to comment

Leave a Reply