C library - strncpy() function



The C library strncpy() function accepts three parameters(dest, src, n) which copies up the n characters from the string pointed to, by src to dest. In this case, the length of src is less than that of n, the remainder of dest will be added with null bytes.

Syntax

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

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

Parameters

This function accepts the following parameter −

  • dest − This is the pointer to the destination array where the content is to be copied.

  • src − This is the string to be copied.

  • n − The number of characters to be copied from source.

Return Value

This function returns the pointer to the copied string.

Example 1

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

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

int main () {
   char src[40];
   char dest[12];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strncpy(dest, src, 10);

   printf("Final copied string : %s\n", dest);
   
   return(0);
}

Output

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

Final copied string : This is tu

Example 2

Below the example shows the utilization of custom string copy with fixed length.

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

void customStrncpy(char* dest, const char* src, size_t n) {
   size_t i;
   for (i = 0; i < n && src[i] != '\0'; i++) {
       dest[i] = src[i];
   }
   
   while (i < n) {
   
   // Fill remaining characters with null terminators
       dest[i] = '\0'; 
       i++;
   }
}

int main() {
   char source[] = "String Copy!";
   
   // Fixed length
   char destination[15]; 
   customStrncpy(destination, source, 10);

   printf("Custom copied string: %s\n", destination);
   return 0;
}

Output

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

Custom copied string: String Cop

Example 3

In this program, the strncpy() copy a fixed-length substring from the source string into the destination string.

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

int main() {
   char source[] = "Hello, Note!";
   
   // Fixed length
   char destination[10]; 
   
   // Copy "Note!"
   strncpy(destination, source + 7, 4); 

   printf("Copied substring: %s\n", destination);
   
   return 0;
}

Output

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

Copied substring: Note
Advertisements