Explain the output of the following C Code. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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]

12th Jun 2019, 6:02 PM
cool_boy12344
cool_boy12344 - avatar
2 Answers
+ 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.
12th Jun 2019, 6:35 PM
Vlad Serbu
Vlad Serbu - avatar
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.
12th Jun 2019, 6:20 PM
Jackson O’Donnell