Bifalgorithm post · Computer science one · Comparisons

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

Why can’t numerical comparison operators be used to compare strings in C? (Computer science one · Comparisons) — "When comparing strings in C, we cannot use th…

Ideas in this flowchart

  • En C, la comparaison de chaînes ne peut pas se faire avec les opérateurs numériques habituels.
  • Les opérateurs == et < ne comparent pas directement le contenu des chaînes.
  • Les chaînes sont représentées comme des tableaux de caractères.
  • Ces opérateurs comparent donc les adresses mémoire des variables.
  • Dans l’exemple, deux zones mémoire sont allouées séparément pour a et b.
  • Les deux chaînes reçoivent pourtant le même contenu : « Hello World! ».
  • Les appels distincts à malloc() produisent deux adresses mémoire différentes.
  • La condition a == b compare ces deux adresses et devient fausse.
  • Le message « strings match! » ne s’affiche donc pas.
Feed/

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

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.