The function should add string1 at the end (there is always room for string2 in string2 ):

 char *strcat(char *string1, const char *string2) { char * str = string1; // теперь str - указатель на первую ячейку массива while (*(++str)); // двигаю str до конца дин. массива типа char while ((*(str++) = *(string2++))); // изменяю значения после '\0' return string1; } 

Testil, like everything works correctly, but falls on the test. Help me find a bug.

  • why didn't you write down the 0-character to the end? - pavel
  • while ((* (str ++) = * (string2 ++))); will stop at the moment when str is 0. - Alexander
  • How exactly falls and on what test? - Qwertiy
  • @Qwertiy I don’t know on which input it falls. And so, the wrong answer. - Alexander
  • @AnT is the wrong answer. - Alexander

1 answer 1

Already in this cycle

 while (*(++str)); 

there is a problem. For example, if the string str empty, then its first character is the terminating zero character '\0' . However, since the pointer is first incremented by ++str , this zero simply slips, and the function has undefined behavior.

Therefore, it will be correct to define the function as follows.

 char *strcat(char *string1, const char *string2) { char *str = string1; // теперь str - указатель на первую ячейку массива while ( *str ) ++str; // двигаю str до конца дин. массива типа char while ( ( *str++ = *string2++ ) ); // изменяю значения после '\0' return string1; } 
  • You are right, thank you. - Alexander