0
#include <stdio.h>
#include <stdlib.h>

int main()
{
  char *s = (char*)malloc(sizeof(char)*5);
  printf("Enter:");
  scanf("%5s",s); //s == abcde

  if(s == "abcde")
  printf("Yes");
  else
  printf("NO");
  
  return 0;
}

I want to check the user given input as above. but it always gives the output as 'NO'. what did i do wrong?

  • OT: You need 6 chars for `s`, that is one more char for the null terminator. But anyway it's pretty pointless to allocate a fixed amount of memory, you can as well have `char s[6];` . – Jabberwocky Aug 17 '21 at 14:23

2 Answers2

1

There are plenty of functions in string.h that do that.

Most common is strcmp()

int strcmp(const char *s1, const char *s2).

If s1 is identical to s2, strcmp() shall return 0.

  if(strcmp(s, "abcde") == 0)
    printf("Yes");

There is also strncmp(), if you want to compare at most n bytes of s1 with s2.

Your malloc() call is wrong, you need one extra byte to handle \0. You can also skip sizeof(char) since its guaranteed to be 1, and you don't have to type cast the result of malloc.

char *s = malloc(5 + 1);
alex01011
  • 1,670
  • 2
  • 5
  • 17
0

You can use strcmp from string.h

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main()
{
  char *s = (char*)malloc(sizeof(char)*5);
  printf("Enter:");
  scanf("%5s",s); //s == abcde

  if(strcmp(s, "abcde") == 0)
    printf("Yes");
  else
    printf("NO");
  
  return 0;
}
Reda Benchraa
  • 239
  • 2
  • 3