Equality of 2 byte arrays/inline c array
I'm programming in objective-c so I can use C as well. I have an array of bytes: (eg)
Byte byteArray[] = {0,0};
And I need to compared to another array which is hard coded. So I'm looking to do something like:
if (byteArray == {0,1}) {
//do something
}
But there is the erro开发者_如何学Gor "Expected Expression" on the curly braces. Is it not possible to have an inline C array?
byte toTest[2] = {0, 1};
if(memcmp(byteArray, toTest, sizeof(toTest)) == 0) { ... }
Or the easier way:
if(byteArray[0] == 0 && byteArray[1] == 1) { ... }
Even if the array wouldn't be "inline" you couldn't do that, because the rvalue of an array is its memory address.
You need to use memcmp
.
You can use mempcmp()
:
Byte otherArray[] = {0, 1};
if (memcmp(byteArray, otherArray, sizeof(byteArray)) == 0) {
// ... equal
}
If you have C99 support, you could also use something like:
memcmp(byteArray, &(Byte[]){0,1}, 2)
... but in my opinion that get's quickly unreadable.
精彩评论