1

What will compare if two character arrays in C language are compared using "==" ?

The answer was Not Equal.

char string1 [] = "Hello";
char string2 [] = "Hello";

if (string1 == string2){
    printf("Equal");
} else {
    printf("Not Equal");
   }
return 0;

}

  • 2
    Check [strcmp](https://linux.die.net/man/3/strcmp) – Rachid K. Dec 02 '20 at 11:02
  • 2
    it will compare the base address of arrays – IrAM Dec 02 '20 at 11:03
  • This is a super-common FAQ. For those who answered it anyway: you can find a list of canonical dupes in the [C tag wiki](https://stackoverflow.com/tags/c/info). Scroll down to FAQ -> Strings. Then close vote as dupe. – Lundin Dec 02 '20 at 12:55

4 Answers4

2

What will compare if two character arrays in C language are compared using "==" ?

Arrays base address will be compared.

If you want to compare the contents of the arrays you need to use strcmp.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
1

string1 and string2 are array names that get converted to pointers to char, so using == will compare those pointers.

Pointer values are memory addresses that are different for each char array, so it is the correct output that you have.

If you want to compare the 2 arrays, then strncmp is an option.

Ron
  • 14,674
  • 4
  • 34
  • 47
Fryz
  • 2,119
  • 2
  • 25
  • 45
1

To better understand run this program and read strcmp

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

int main()
{
    char string1 [] = "Hello";
    char string2 [] = "Hello";
    // checking base address of string1 and string2, which will not be equal
    if (string1 == string2) {
        printf("Equal : string1 = %u and string2 = %u\n", string1, string2);
    } else{
        printf("Not Equal : string1 = %u and string2 = %u\n", string1, string2);
    }
    // strcmp checks the contents that are stored in string1 and string2
    if(strcmp(string1, string2) == 0) {
        printf("Equal\n");
    }else {
        printf("Not Equal\n");
    }
    return 0;
}
IrAM
  • 1,720
  • 5
  • 18
0

You just use strcmp to check if the two string are equal or no

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

int main()
{
    char string1 [] = "Hello";
    char string2 [] = "Hello";
    if(strcmp(string1, string2) == 0)
    {
         printf("Equal\n");
    }
    else 
    {
         printf("Not Equal\n");
    }
    return 0;
}
MED LDN
  • 684
  • 1
  • 5
  • 10