C strncat()

« Previous Chapter Next Function »


The strncat() function concatenates not more than count characters of the string pointed to by str2 to the string pointed to by str1 and terminates str1 with a null. The null terminator originally ending str1 is overwritten by the first character of str2. The string str2 is untouched by the operation. If the strings overlap, the behaviour is undefined.

The strncat() function returns str1.

Remember that no bounds checking takes place, so it is the programmer's responsibility to ensure that str1 is large enough to hold both its original contents and also those of str2.

strncat() Syntax

Following is the syntax of the strncat() function :

char *strncat(char *str1, const char *str2, size_t count);

strncat() Example

Following program appends the first string read from stdin to the second and prevents an array overflow from occurring to s1. For example, assuming the user enters hello and there, the program prints therehello.

void main()
	char s1[80], s2[80];
	unsigned int len;
	/* compute how many chars will actually fit */
	len = 79-strlen(s2);
	strncat(s2, s1, len);

« Previous Chapter Next Function »