0
Explain the output of the following C Code.
CODE : #include <stdio.h> int main() { char arr[10] = {'a','b','\0','d'}; printf("%s\n",arr); if(arr == "ab") printf("true"); else printf("false"); } OUTPUT : ab false [Why not : ab true]
2 Respuestas
+ 2
Because arr == "ab" compares the pointer to the second ab, which is stored in the .data segment, and the pointer to arr.
The strcmp function from string.h compares 2 strings. It returns 0 if they are equal.
if (strcmp(arr, "ab") == 0) should give you the desired result.
0
Two reasons:
A) when you say arr == x, you are comparing the address of the first value in arr (not the contents of arr) to x.
B) even if == was a .compareTo function, it would look loop through every char in arr, which includes 'd'. The print string abikity in printf just prints until the first null character.