What is the output of the following code?char str1[] = "abc";char str2[] = "abc";if (str1 == str2) printf("Equal\n");else printf("Not Equal\n");
Question
What is the output of the following code?char str1[] = "abc";char str2[] = "abc";if (str1 == str2) printf("Equal\n");else printf("Not Equal\n");
Solution
The output of the code will be "Not Equal".
Here's why:
In C, when you declare a string as an array of characters, the variable actually holds the address of the first character in memory. So, when you compare str1 and str2 using ==, you're actually comparing the addresses in memory of the two strings, not the contents of the strings themselves.
Even though str1 and str2 have the same content ("abc"), they are two different arrays stored at two different locations in memory. Therefore, str1 == str2 is false, and "Not Equal" is printed.
If you want to compare the contents of the strings, you should use the strcmp() function from the string.h library.
Similar Questions
What is the output of the following code?char str1[] = "abc";char str2[] = "def";int result = strcmp(str1, str2);if (result < 0) printf("str1 is less than str2\n");else if (result > 0) printf("str1 is greater than str2\n");else printf("str1 is equal to str2\n");
What will be the output of the following C code? #include <stdio.h> int main() { char *str = "hello, world"; char *str1 = "hello, world"; if (strcmp(str, str1)) printf("equal"); else printf("unequal"); }
1.What is the output of the following code?char str[] = "hello";printf("%c\n", str[1]);
What is the output of the following code?char str1[] = "C programming";char str2[20];strcpy(str2, str1);printf("%s\n", str2);
#include <stdio.h> int main() { char *str = "hello, world"; char *str1 = "hello, world"; if (strcmp(str, str1)) printf("equal"); else printf("unequal"); } equalunequalCompilation error Depends on the compiler
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.