when I use strcmp
:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *i, *j;
scanf("%s %s", &i, &j);
if (strcmp(i, j) == 0){
printf("Same \n");
} else {
printf("different\n");
}
}
output: gives no output just blank
When I directly compare i & j
#include <stdio.h>
#include <string.h>
int main(void)
{
char *i, *j;
scanf("%s %s", &i, &j);
if (i == j) {
printf("Same \n");
} else {
printf("different\n");
}
}
output : Same
Ye that's all I tried by replacing i == j
with strcmp()
.
CodePudding user response:
The problem is not related to the use of strcmp
, you have undefined behavior in the way you use scanf()
to read strings. You pass the addresses of string pointers where scanf()
expects addresses of char
arrays.
In both cases, the behavior is undefined and indeed the first program causes a segmentation fault, whereas the second seems to produce expected behavior, only by chance because the entered strings are short. Try longer strings and you might get a segmentation fault as well.
Here is a modified version with defined behavior:
#include <stdio.h>
#include <string.h>
int main(void) {
char i[100], j[100];
if (scanf("