C library - strncat() function



The C library strncat() function takes three variable as parameters which appends the string pointed to by src to the end of the string pointed to by dest up to n characters long.

Below are some key points that highlight its importance −

  • It prevent the buffer overflow
  • It control over string size.
  • This function safely handle the string.
  • It maintain the integrity and robustness of software application.

Syntax

Following is the syntax of the C library function strncat()

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

Parameters

This function accepts the following parameter −

  • dest − This is pointer to the destination array, which should contain a C string, and should be large enough to contain the concatenated resulting string which includes the additional null-character.

  • src − This is the string to be appended.

  • n − This is the maximum number of characters to be appended.

Return Value

This function returns a pointer to the resulting string dest.

Example 1

Following is the basic C library program that demonstrates the usage of strncat() function.

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

int main () {
   char src[50], dest[50];

   strcpy(src,  "This is source");
   strcpy(dest, "This is destination");

   strncat(dest, src, 15);

   printf("Final destination string : |%s|", dest);
   
   return(0);
}

Output

The above code produces the following result −

Final destination string : |This is destinationThis is source|

Example 2

In this example, we utilize the concatenation of fixed-length substring from the source string to the destination string using strncat().

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

int main() {
   char dest[20] = "Hello, ";
   char src[] = "Beautiful World!";

   // Append "World"
   strncat(dest, src + 10, 5); 

   printf("Concatenated substring: %s\n", dest);
   return 0;
}

Output

After executing the above code, we get the following result −

Concatenated substring: Hello, World

Example 3

Below the program demonstrates the source string to the destination string by ensuring a fixed length.

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

void customStrncat(char* dest, const char* src, size_t n) {
   size_t dest_len = strlen(dest);
   size_t i;

   for (i = 0; i < n && src[i] != '\0'; i++) {
       dest[dest_len + i] = src[i];
   }
   
   // Null-terminate the result
   dest[dest_len + i] = '\0'; 
}

int main() {
   char dest[20] = "Hello, ";
   char src[] = "World!";

   // Append "World"
   customStrncat(dest, src, 5); 

   printf("Custom concatenated string: %s\n", dest);

   return 0;
}

Output

On execution of above code, we get the following result −

Custom concatenated string: Hello, World
Advertisements