GeeksforGeeks » Interview Questions
Adobe Interview Question for Software Engineer/Developer (Fresher) about Aptitiude, Arrays, Data Str
(6 posts)-
Predict the Output:
#include<stdio.h> void main() { char ch1[]="hello", ch2[]="hello"; if (ch1==ch2) printf("Equal\n"); else printf("Unequal\n"); }I executed this on Linux terminal and got the answer as Unequal. Can anyone please explain how this is happening?
-
coz array names are resoluted to their starting address. hence when you are comparing, you are actually comparing the addresses of two variables ch1 and ch2 which are different
-
Hi,
But in C there is a concept called "Shared Strings".
That is, if the same string contains more then one pointers, and if Shared string feature is on,
then both the ptrs refer to the same location in memory. In such cases, u ll get "equal". -
Shared string works if the the code was as below ,
#include<stdio.h>
void main()
{
char *ch1 = "sample";
char *ch2 = "sample";
if (ch1==ch2)
printf("Equal\n");
else
printf("Unequal\n");
}I.e in case of pointer both point to same location but in case of arrays they point differ.
-
yes vangat you are right..
-
The actual answer for this is you cannot check two strings using == operator ,in case of strings you need to use string compare,that is the actual answer ..
Reply
You must log in to post.