Concatenate Strings with strcat() in C++: Safe Example
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
strcat() appends a null-terminated C-style string to another null-terminated C-style string. In the example, destination is a fixed-size character array initialized with "Hello", while source points to ", C++!". Calling std::strcat(destination, source) finds the null terminator in destination, then copies characters from source starting at that position and adds a new null terminator. The program prints the concatenated result and its length.
The second part uses std::strncat() to append " Welcome!" while limiting the number of copied characters. This helps avoid overflowing the destination buffer when the available space is known. The maximum append count is calculated as sizeof(destination) - std::strlen(destination) - 1, preserving room for the null terminator.
Inputs: two null-terminated character arrays or C-style strings. Outputs: the modified destination string and its length. Time complexity: O(n + m), where n is the length of the destination before concatenation and m is the number of characters appended, because strcat() must locate the destination terminator and then copy the source characters. Always ensure the destination buffer is large enough; prefer std::string or strncat() for safer string handling.