Question

Is it possible to use a range when using memcpy or memcmp?

char data[900000]; // size 900000
char array[20]; // size 20

if (memcmp(data[50-70], array, 20) == 0) {
    // do thing
}

I'd like to be able to compare the (20) keys data[50-70] with array[]

Was it helpful?

Solution

memcmp / memcpy simply take a pointer to the data you want to compare or copy.

Thus, you can essentially copy or compare any "range" by providing a pointer to the start of the data you wish to compare and the length of the data, pretty much as you have done above.

Adjust your code above as follows:

if (memcmp(&data[50], array, 20) == 0) {
    // do thing
}

This tells memcmp to start checking at the address of the 50th subscript of the data array, and to compare that to the data at the address of array, and to check 20 elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top