Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a char array in C

Tags:

c

string

pointers

I am not a C developer or know much about C but I came across this C interview question:

int toto(char *a, char *b){
    while(*a++ == *b++);
    return(*a == 0 && *b == 0);
}

I spent a good amount of time trying to figure it out and after reading a few things online I kind of grasped what it is trying to do but there are still some weird behaviours that arise. From what I understand (please correct me if I'm wrong), this piece of code will go through two strings (char arrays) and determine whether they are equal up until the last character and returns true only if the last character is different. return (*a == 0 && *b == 0) checks for the 0 integer that all strings end with in C. This only happens after the loop has exited i.e when two characters aren't equal before the increment happens; so if the last two characters are not equal, it will increment them to the 0 int and go through to the return statement. I also noticed that that if the strings differ by 1 then it still returns true if the strings are equal up until n-1 for example:

char a[] = "ggr"
char b[] = "ggre"
//returns 1
char a[] = "ggr"
char b[] = "ggf"
//returns 1

I found this behaviour peculiar but the test case that I can't understand is the following:

char a[] = "abcd";
char b[] = "abcd";
//returns 1
char a[] = "abc"
char b[] = "abc"
//returns 0

I understand why abc returns false but I have no idea why it wouldn't return the same for abcd. To me, it seems like it treats strings of different lengths differently but the code doesn't seem to care about the length.

Can anyone explain what the code intends to do and why the code behaves differently when given different lengths of strings. I have a feeling it has to do with the order of precedence for certain operators but I couldn't find an answer.

Edit: It seems the code supplied by the interview is buggy on purpose, I was under the impression that the code is valid.

like image 488
ybce Avatar asked Dec 14 '22 18:12

ybce


1 Answers

Your code has undefined behavior. It will eventually access memory beyond the null terminated char array. This code is wrong in that sense.

The correct implementation would be something like

int toto(char *a, char *b){
    while(*a && *b && *a == *b) a++,b++;
    return (*a - *b)?0:1;
}
like image 111
user2736738 Avatar answered Dec 26 '22 16:12

user2736738