What is wcsncpy in C?

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.

Parameters

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.

Return value

The function returns the pointer to the modified destination wide string.

Example

#include<stdio.h>
#include<wchar.h>
void main() {
// declaring and initializing wide strings
wchar_t str1[] = L"HELLO WORLD";
wchar_t str2[15] = L"";
wchar_t str3[15] = L"";
// calling the function
wcsncpy(str2, str1, 5);
wcsncpy(str3, str1, 15);
// incorrect function call:
// wcsncpy(str3, str1, 20);
// using the wprintf function to print the wide strings
wprintf(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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved