strncat() — Concatenate strings
Standards
| Standards / Extensions | C or C++ | Dependencies |
|---|---|---|
ISO C
POSIX.1 XPG4 XPG4.2 C99 Single UNIX Specification, Version 3 |
both |
Format
#include <string.h>
char *strncat(char * __restrict__string1, const char * __restrict__string2, size_t count);General description
The strncat()
built-in function appends the first count characters
of string2 to string1 and
ends the resulting string with a NULL character (\0).
If count is greater than the length of string2,
strncat() appends only the maximum length of string2 to string1.
The first character of the appended string overwrites the terminating
NULL character of the string pointed to by string1.
If copying takes place between overlapping objects, the behavior is undefined.
Returned value
strncat() returns the value string1, the concatenated string.
Example
CELEBS44
/* CELEBS44
This example demonstrates the difference between &strcat. and
&strncat..
&strcat. appends the entire second string to the first,
whereas &strncat. appends only the specified number of
characters in the second string to the first.
*/
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char buffer1[SIZE] = "computer";
char * ptr;
/* Call strcat with buffer1 and " program" */
ptr = strcat( buffer1, " program" );
printf( "strcat : buffer1 = \"%s\"\n", buffer1 );
/* Reset buffer1 to contain just the string "computer" again */
memset( buffer1, '\0', sizeof( buffer1 ));
ptr = strcpy( buffer1, "computer" );
/* Call strncat with buffer1 and " program" */
ptr = strncat( buffer1, " program", 3 );
printf( "strncat: buffer1 = \"%s\"\n", buffer1 );
}
Output
strcat : buffer1 = "computer program"
strncat: buffer1 = "computer pr"