-3

stuck in array and string compare with strcmp c why ist it working?? compiler got stuck at if(strcmp(c,ch[i]) == 0){

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

int main(){
    char ch[]="asdfghjkl";
    char c;
    int n=sizeof(ch)/sizeof(char);
    scanf("%c",&c);
    for(int i=0;i<n;i++){
        if(strcmp(c,ch[i]) == 0){
            printf("%c is in %d\n",c,i+1);
            break;
        }else if(i==n-1){
            printf("%c not fond\n",c);
        }
    }
    return 0;
}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
FAHIM
  • 19
  • 1
  • 3

2 Answers2

1

I believe your compiler should complain that you're using strcmp incorrectly: You are passing two chars to two const char*s which is definitely a UB. It'd be good if your compiler stops you from doing so by throwing an error.

The prototype for strcmp is (in string.h)

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

Since you have two chars and char is a basic type, you can compare them directly:

if ( c == ch[i] )
iBug
  • 35,554
  • 7
  • 89
  • 134
  • 1
    It is not "UB", it is a constraint violation of the allowed forms of simple assignment. When passing parameters to a function, "...the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters" (6.5.2.2/7). Going from `char` to `char*` is not a valid form. Meaning that the compiler must give a diagnostic or it is not conforming. – Lundin Aug 25 '17 at 13:20
0

Declaration of strcmp: int strcmp(const char *s1, const char *s2);

strcmp expects strings, but you are trying to pass char.

Use

if (c == ch[i])
Ritesh
  • 1,809
  • 1
  • 14
  • 16