1

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

1

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.

Paige DePol
  • 1,121
  • 1
  • 9
  • 23
  • oh wow that's awesome. one more question — let's say i had an integer `n = 10` would this work: `if (memcmp(&data[50+n], array, 20) == 0)`? –  Jan 28 '14 at 02:20
  • 1
    Yes, it would start checking at the address of the 50th + n element of your array. If you are new to C and pointers in general I would strongly suggest reading some pointer tutorials online as they are a fundamental part of the language and obtaining a solid understanding of them early will help you considerably! :) – Paige DePol Jan 28 '14 at 02:21