Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is wcsncpy in C?

Amaaz Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

c

CONTRIBUTOR

Amaaz Ahmad
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring