I have the below code.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isValid(char* s) {
int size = strlen(s);
char array[] = {'(', ')', '[', ']', '{', '}'};
printf("%c",*s); //This gives me )
printf("%c\n",*(s + 1)); //This gives me (
for (int i = 0; i < size; i++) {
if ((*(s + i)==array[0]) && (*(s + size - i - 1)==array[1])){
printf("%c",*(s + i)); //This gives me (
printf("%c\n", *(s + size - i - 1)); //This gives me )
printf("%c\n", array[0]); //This gives me (
return true;
}
}
return false;
}
int main() {
char str[] = ")(";
if (isValid(str)) {
printf("The string is valid\n"); //this gets printed
} else {
printf("The string is not valid\n");
}
return 0;
}
So, I am passing a string array to a function, where the first character is ")" and second character is "(".
The issue is that when I try to compare the first character ")" with the first character in "array" array ("("), in the for loop inside the "isValid" function, somehow, both the character are equal and the statement "return true" executes.
On further debugging, I found that the first element changes of the input "s" array changes to "(". I do not understand why.
Please check my comments in the code (marked infront of the printf statements). Can someone help explaining why?
Thanks.
In the second iteration of your loop,
*(s + size - i - 1)evaluates to*(s + 2 - 1 - 1), i.e.*(s+0).This means that you're comparing
s[1]witharray[0]ands[0]witharray[1], and thus your test succeeds.