-1

I'm writing a c++ script that compare chars of two strings one by one using strcmp(). I wrote this code:

        char test1[1];
        char test2[1];
        test1[0]=str1[i];  //str1 is a char array
        test2[0]=str2[i];  //str2 is a char array
        int result=strcmp(test1,test2); 

but if I print test1 or test2 I encountered with two chars. for example if first index of str1='a' then test1 is "aa" but I don't know why? Please Help.

Imaney
  • 1
  • 2
  • 4
    `strcmp()` requires a C-style null-terminated string. `test1[1]` doesn't have room for a character and the terminator. – Barmar Jun 23 '21 at 00:06
  • 2
    `strcmp` is for comparing NUL terminated C-strings not individual characters. To compare characters just use `==` like `str1[i] == str2[i]` – kaylum Jun 23 '21 at 00:07

1 Answers1

3

strcmp() takes null-terminated strings, but neither of your char[] arrays are null-terminated.

char test1[2]; // <-- increase this!
char test2[2]; // <-- increase this!
test1[0] = str1[i];
test1[1] = '\0'; // <-- add this!
test2[0] = str2[i];
test2[1] = '\0'; // <-- add this!
int result = strcmp(test1, test2); 

Otherwise, you can use strncmp() instead, which does not require null terminators, so no char[] arrays are needed, eg:

char test1 = str1[i];
char test2 = str2[i];
int result = strncmp(&test1, &test2, 1);

Or simply:

int result = strncmp(&str1[i], &str2[i], 1);
// or:
// int result = strncmp(str1+i, str2+i, 1);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770