Latest web development tutorials

C library functions - strncpy ()

C standard library - <string.h> C standard library - <string.h>

description

C library functionschar * strncpy (char * dest, const char * src, size_t n) to copy the string pointed to by srcdest, copy up toncharacters. When the length of src is less than n, the remainder of dest will be padded with null bytes.

statement

Here is () statement strncpy function.

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

parameter

  • dest - point to the destination array for storing copy content.
  • src - the string to be copied.
  • n - the number of characters copied from the source.

return value

This function returns a string of the final copy.

Examples

The following example demonstrates the strncpy () function is used. Here, we use the function memset () to clear the memory location.

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

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

   printf("最终的目标字符串: %s\n", dest);
   
   return(0);
}

Let's compile and run the above program, which will result in the following:

最终的目标字符串: This is w3

C standard library - <string.h> C standard library - <string.h>