The wcsncpy
function is used to copy the contents of one wide string into another wide string. The function stops when it encounters null characters or the specified number of characters are copied. The wcsncpy
function is defined in the wchar.h
header.
wchar_t* wcsncpy (wchar_t* destination, const wchar_t* source, size_t num);
The function takes three parameters.
In the above snippet of code, we’re copying the contents of source
into the destination
. The wide characters are copied from source
to destination
until the num
number of characters are copied, or null wide character is encountered.
If the length of source
is less than num
, the remaining indices are filled with null wide characters.
If the length of the source is greater than num
, the resulting destination
string might not be null terminated.
The function returns the pointer to the modified destination
wide string.
#include<stdio.h>#include<wchar.h>void main() {// declaring and initializing wide stringswchar_t str1[] = L"HELLO WORLD";wchar_t str2[15] = L"";wchar_t str3[15] = L"";// calling the functionwcsncpy(str2, str1, 5);wcsncpy(str3, str1, 15);// incorrect function call:// wcsncpy(str3, str1, 20);// using the wprintf function to print the wide stringswprintf(L"str2: %ls\n\n", str2);wprintf(L"str3: %ls\n\n", str3);}
In the above example, str1
's content is being copied into str2
with a limit of 5 characters and str3
with 15 characters.
If the function is called with num
greater than the source
's length, the program might crash, or the resultant destination
string might not be null terminated. Such an incorrect function call is shown as a comment in line 16.
Free Resources