What is strncat() Function in C language?

In C, the strncat() function is used to concatenate a specified number of characters from one string to the end of another string. It appends at most n characters from the source string to the destination string.

Syntax

char *strncat(char *dest, const char *src, size_t n);

Parameters

  • dest − Pointer to the destination string where characters will be appended
  • src − Pointer to the source string from which characters will be copied
  • n − Maximum number of characters to append from source

Return Value

The function returns a pointer to the destination string dest.

Example 1: Basic Usage

The following program demonstrates basic usage of strncat() function −

#include <stdio.h>
#include <string.h>

int main() {
    char dest[30] = "Hello ";
    char src[] = "TutorialsPoint";
    
    printf("Before concatenation:<br>");
    printf("Destination: %s<br>", dest);
    printf("Source: %s<br>", src);
    
    /* Concatenate first 5 characters from src to dest */
    strncat(dest, src, 5);
    
    printf("\nAfter concatenation:<br>");
    printf("Result: %s<br>", dest);
    
    return 0;
}
Before concatenation:
Destination: Hello 
Source: TutorialsPoint

After concatenation:
Result: Hello Tutor

Example 2: Safety with Buffer Size

This example shows how strncat() helps prevent buffer overflow −

#include <stdio.h>
#include <string.h>

int main() {
    char dest[20] = "C ";
    char src[] = "Programming Language";
    
    printf("Destination buffer size: 20<br>");
    printf("Initial string: %s<br>", dest);
    printf("Source string: %s<br>", src);
    
    /* Safely concatenate only 10 characters */
    strncat(dest, src, 10);
    
    printf("After strncat with n=10: %s<br>", dest);
    printf("Length: %zu<br>", strlen(dest));
    
    return 0;
}
Destination buffer size: 20
Initial string: C 
Source string: Programming Language

After strncat with n=10: C Programmin
Length: 12

Key Points

  • The destination string must have enough space to hold the concatenated result
  • strncat() automatically adds a null terminator at the end
  • If the source string has fewer than n characters, only the available characters are copied
  • The function modifies the destination string in place

Conclusion

The strncat() function provides a safe way to concatenate strings by limiting the number of characters copied. It helps prevent buffer overflow and is essential for secure string manipulation in C programming.

Updated on: 2026-03-15T13:24:07+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements