C Standard Library

C <wchar.h> - wcsncpy() Function

The C <wchar.h> wcsncpy() function is used to copy the first num characters of the wide string pointed to by source, including the null character, to the wide character array whose first element is pointed to by destination.

If the end of the source is found before num characters, destination is padded with additional null wide characters until a total of num characters is reached. If num is reached before the entire string source was copied, the destination is not null-terminated.

The behavior is undefined if the strings overlap.


wchar_t* wcsncpy (wchar_t* destination, const wchar_t* source, size_t num);


destination Specify pointer to the wide character array where the content is to be copied.
source Specify pointer to the null-terminated wide string to copy from.
num Specify maximum number of characters to copy.
size_t is an unsigned integer type.

Return Value

Returns destination.


The example below shows the usage of wcsncpy() function.

#include <stdio.h>
#include <wchar.h>
int main (){
  wchar_t str1[100] = L"xyz";
  wchar_t str2[100];
  wchar_t str3[100] = L"Hello World!";

  //replacing the content of str1 and
  //str2 with first 5 characters of str3
  wcsncpy(str1, str3, 5);
  wcsncpy(str2, str3, 5);
  //null character manually added to str2
  str2[5] = L'\0';

  printf("str1 is: %ls\n", str1);
  printf("str2 is: %ls\n", str2);   
  return 0;

The output of the above code will be:

str1 is: Hello
str2 is: Hello

❮ C <wchar.h> Library