Saqib Ali
Saqib Ali

Reputation: 4448

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.?

Upvotes: 0

Views: 66

Answers (1)

chux
chux

Reputation: 154601

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 when char is signed and uses non-2's compliment encoding (think -0). Not much risk of that theses days. Solution: access data as unsigned char. ((unsigned char *)arr1)[i] != ((unsigned char *)arr2)[i].

Upvotes: 1

Related Questions