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 numeric comparison operators be used to compare strings in C?ComputerScienceOne · Comparing Strings and Characters
- Why can numeric comparison operators not be used to compare strings in C?ComputerScienceOne · Order of Precedence
- How can qsort() sort an array of strings using pointers?ComputerScienceOne · Sorting Pointers to Elements
- How can comparison operators be used with characters in C?ComputerScienceOne · Comparing Strings and Characters
- How can you create static strings with character arrays?ComputerScienceOne · Character Arrays
- How do you compare strings in Java?ComputerScienceOne · Comparisons
- How can comparator functions order Student structures?ComputerScienceOne · Comparator Functions
- How are comparison operators used with characters in C?ComputerScienceOne · Order of Precedence