'comparing two arrays in c using a for loop
I have two char arrays of different lengths. I want to make sure that the first 256 elements are same.
I am using the following:
for (int i = 0; i < 256; i = i + 1) {
if (arr1[i] != arr2[i]) {
not_equal = 1;
}
}
Will this catch all cases of special characters etc.?
Solution 1:[1]
Will this catch all cases of special characters etc.?
Yes, except:
If either array is less than 256 elements, code attempts to access outside array bounds - which is undefined behavior (UB). @Oka
arr1[i] != arr2[i]can fail whencharis signed and uses non-2's compliment encoding (think -0). Not much risk of that theses days. Solution: access data asunsigned char.((unsigned char *)arr1)[i] != ((unsigned char *)arr2)[i].
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
