-2

The below code compares s[2] with the string "sw". Since I have assigned s[2] = "sw", shouldn't it return 1 when I use strcmp. But I am getting 0 as the value of i.

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

int main () {
  char s[2] = "sw";
  int i;
 
  i = strcmp(s, "sw");

  printf("%d",i);
}

1 Answers1

0

C stringss require to be null character terminated. So the char array holding it has to have space for it.

int main () {
  char s[3] = "sw"; 
  int i;
 
  i = strcmp(s, "sw");

  printf("%d",i);
}

https://godbolt.org/z/1Gs8WqG5h

0___________
  • 60,014
  • 4
  • 34
  • 74