Search code examples
cstringstrcmp

Why strcmp giving different response for complete filled character array?


#include <stdio.h>
#include <string.h>
void main()
{
  char a[10]="123456789";
  char b[10]="123456789";
  int d;
  d=strcmp(a,b);

  printf("\nstrcmp(a,b) %d", (strcmp(a,b)==0) ? 0:1);
  printf("compare Value %d",d);
}

Output:

strcmp(a,b) 0
compare value 0

If the same program response is different when increase the array to full value, I mean 10 characters. That time the values are different.

#include <stdio.h>
#include <string.h>
void main()
{
  char a[10]="1234567890";
  char b[10]="1234567890";
  int d;
  d=strcmp(a,b);

  printf("\nstrcmp(a,b) %d", (strcmp(a,b)==0) ? 0:1);
  printf("compare Value %d",d);
}

Output:

strcmp(a,b) 1
compare value -175

Why strcmp responding differently when the string is reached full value of array ?


Solution

  • The behaviour of your second snippet is undefined.

    There's no room for the null-terminator, which is relied upon by strcmp, when you write char a[10]="1234567890";. This causes strcmp to overrun the array.

    One remedy is to use strncmp.

    Another one is to use char a[]="1234567890"; (with b adjusted similarly) and let the compiler figure out the array length which will be, in this case, 11.