Hello everyone.
I have been trying to solve one competitive problem on Contest Page | CodeChef.
While trying to compare two strings, I used if statement
Code:
if(ar[i].string==ar[j].string)
instead of strcmp
Code:
if(strcmp((ar[i].string), ar[j].string) == 0)
.
But the result seems to be different even when both the strings are same. Once I change the if statement with the strcmp, it works perfectly and as per expectation.
Here is the snippet of code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long u32;
typedef char s8;
typedef int s16;
typedef long s32;
#define scan(x) int x; scanf("%d", &x);
#define lscan(x) u32 x; scanf("%ld", &x);
#define scanloop(ctr,x) {int i; for(i=0;i<ctr;i++) scanf("%d", x);}
#define printloop(ctr,x) {int i; for(i=0;i<ctr;i++) printf("%d\n", x);}
#define printdata(x) printf("%d\n", x);
#define selfprint(x) printf(x);
#if 1
int main()
{
typedef struct sr
{
u8 string[20];
}sr;
lscan(loop)
while(loop--)
{
lscan(n)
sr ar[100001]={0};
u32 ctra=0, ctrb=0,indexa=0, indexb=0;
for(int i=0,j=0; i<n; i++)
{
scanf("%s", ar[i].string);
}
for(int i=0,j=0; i<n; i++)
{
if(ar[i].string==ar[j].string) //not working statement
//if(strcmp((ar[i].string), ar[j].string) == 0) //Issue seems to be here
{
ctra++;
indexa = i;
}
else
{
ctrb++;
indexb = i;
}
}
if(ctra>ctrb)
{
printf("%s\n", ar[indexa].string);
}
else if(ctrb>ctra)
{
printf("%s\n", ar[indexb].string);
}
else
selfprint("Draw\n")
}
return 0;
}
#endif // 1
Could anyone tell why it is so? Answers seems different when I entered:
When I enable the if condition, result become "ab" but when I used strcmp if becomes "Draw" which is expected.
Apology if question seems stupid also if code looks chaos but please let me know if something bothered anyone.
Thanks in advance.