A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_strncpy.htm below:

C library - strncpy() function

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 −

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4