C++ wcsncpy()

The wcsncpy() function in C++ copies a specified number of wide characters from source to destination.

The wcsncpy() function is defined in <cwchar> header file.

wcsncpy() prototype

wchar_t *wcsncpy( wchar_t *dest, const wchar_t *src, size_t count );

The wcsncpy() function takes three arguments: dest, src and count. It copies a maximum of count wide characters from the wide string pointed to by src to the memory location pointed to by dest.

If count is less than the length of src, first count characters are copied to dest and it is not null terminated. If count is more than the length of src, all the wide characters from src is copied to dest and additional terminating null wide characters are added until a total of count wide characters have been written.

The behaviour is undefined if the two wide strings overlap.

wcsncpy() Parameters

  • dest: Pointer to a wide character array where the contents are copied to.
  • src: Pointer to a wide character array where the contents are copied from.
  • count: Maximum number of wide characters to copy.

wcsncpy() Return value

  • The wcsncpy() function returns dest.

Example: How wcsncpy() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

int main()
	setlocale(LC_ALL, "en_US.utf8");
	wchar_t src[] = L"\u0166\u0113\u010b\u0127\u0149\u0151\u013c\u014c\u0123\u0194";
	wchar_t dest[] = L"Hello Hi";
	wcout << L"Before copying, dest = " << dest << endl;
	wcsncpy(dest, src, 4);
	wcout << L"After copying, dest = " << dest << endl;
	return 0;

When you run the program, the output will be:

Before copying, dest = Hello Hi
After copying, dest = Ŧēċħo Hi
Did you find this article helpful?