Concept

Why can’t numerical comparison operators be used to compare strings in C?

ComputerScienceOne / Comparisons

"When comparing strings in C, we cannot use the numerical comparison operators such as ==, or <. Because strings are represented as arrays, using these operators actually compares the variable’s memory addresses. For example:\n\n1 char *a = (char *) malloc(sizeof(char) * 13);\n\n2 char *b = (char *) malloc(sizeof(char) * 13);\n\n3 strcpy(a, \"Hello World!\");\n\n4 strcpy(b, \"Hello World!\");\n\n5\n\n6 if(a == b) {\n\n7 printf(\"strings match!\n\n\");\n\n8 }\n\nThe code above will not print anything even though the strings a and b have the same content. This is because a == b is comparing the memory address of the two variables. Since they point to different memory addresses, created by two separate calls to malloc(), they are not equal."

Related Ideas

Why can’t numerical comparison operators be used to compare strings in C? | ComputerScienceOne | Bifalgorithm | Bifalgorithm