Challenge: Implement memcmp

Test your knowledge by solving this coding challenge.

The memcmp function

The memcmp function comes from the C standard library. It allows us to compare two memory areas for equality at the byte level.

The header is as follows:

int memcmp(const void* ptr1, const void* ptr2, size_t num);

It compares the first num bytes of ptr1 against the first num bytes of ptr2. It returns the following:

  • < 0 if the blocks are not equal and the first byte that doesn’t match is smaller in ptr1 than ptr2.
  • = 0 if the blocks are equal.
  • > 0 if the blocks aren’t equal and the first byte that doesn’t match is bigger in ptr1 than ptr2.

The return values are similar to those of strcmp. However, the difference is that strcmp stops comparing when it encounters the end of string character '\0', while memcmp compares exactly num bytes.

It’s the caller’s job to ensure that ptr1 and ptr2 contain at least num bytes.

Input and output

Example 1:

int x = 5;
int y = 5;

int result = memcp(&x, &y, sizeof(int));

The result is 1 since x and y contain the same value.

Example 2:

int x = 5;
int y = 7;

int result = memcp(&x, &y, sizeof(int));

The result is a value smaller than 0 since x and y are different and x is smaller than y in lexicographic order.

We can also compare arrays, strings, and user-defined data types (structures).

Challenge

Implement the function my_memcmp, which should mimic the functionality of memcmp. Don’t include string.h, and don’t use the original memcmp function. Write your own implementation.

The complexity should be O(n)O(n), that is, use a single for loop.

Get hands-on with 1400+ tech skills courses.