1. The strncat function in C
The problem that this function helps to solve is of string (or character array) concatenation. If you
have a character array that has more memory than it uses. And you would like to use this memory instead
and replace unused bytes with desired characters, then strncat
is a perfect candidate. To see this in a
more concrete example, consider this code:
Example 1: Usage of the strncat in C.
#
include
<stdio.h>
#
include
<string.h>
int
main
()
{
char
dest[24] =
"Practice makes "
;
char
dest2[24] =
"Practice makes "
;
char
*src =
"perfect!"
;
strncat
(dest, src, 5);
strncat
(dest2, src, 8);
printf
(
"When n is 5: %s\n"
, dest);
printf
(
"When n is 8: %s\n"
, dest2);
return
0;
}
Possible output:
When n is 8: Practice makes perfect!
From the example above, we can already make a couple of deductions about the behavior of this function.
(1) The strncat
function modifies the destination array that we
pass as the first argument. (2) Number of elements that are copied from the source string depend on the
third argument. When we passed 5 as an argument (on line 8), we copied perfe
. When we passed 8 as an argument (on line 9), we
copied perfect!
.
How lovely this behavior may seem, there are a couple of drawbacks that are worthy of knowing before
you add the strncat
function to your project. The drawbacks
manifest when (1) the destination and the source arrays overlap in memory, (2) when the destination
array does not have enough memory to contain characters from the source string.