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[]

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top