liveBook · Manning

Wide character string

As explained in Modern C, Third Edition

A wide character string is a null-terminated array of wchar_t values representing characters from an extended character set.

A wide character string (WCS) is a null-terminated array of wchar_t values, with one wide character representing each character of an extended character set. It provides a wide-character counterpart to an ordinary char string. section 14.3

Converting a multibyte string

The mbsrtowcs function converts a multibyte string into a WCS. A dynamically allocated result needs space for the converted characters and its terminating wide null character; invalid input must be handled before conversion. section 14.3

Working with wide character strings involves these distinctions:

  • Use wcs-prefixed functions for operations that ordinary str functions do not perform correctly on wide character strings, including counting, searching, and matching. section 14.3
  • Treat wchar_t encoding as implementation-dependent; modern platforms commonly use 16- or 32-bit representations, while Unicode support can be checked with implementation macros. section 14.3
 wchar_t* mbsrdup(char const*s, mbstate_t*restrict state) {
   mbstate_t st =  state ? *state : *MBSTATE;
   size_t mblen = mbsrlen(s, &st);
   if (mblen == mbinvalid) return nullptr;
   wchar_t* S = malloc(sizeof(wchar_t[mblen+1]));
   /* We know that s converts well, so no error check */
   if (S) mbsrtowcs(S, &s, mblen+1, state);
   return S;
 }

Inspect a complete conversion pattern that measures a multibyte string, allocates a wchar_t array, and converts the data. section 14.3

How Modern C, Third Edition covers it

How deep it goes
Defines representation and conversion, then addresses string functions, invalid input, and wchar_t portability without fully specifying encodings.
Examples
Uses mbsrdup to allocate and populate a wide string after measuring a multibyte source.
What it assumes
Assumes familiarity with C strings and introduces wchar_t arrays, multibyte conversion, and conversion state.
What you can do after
Apply it via C library functions to convert multibyte strings and perform wide-character string operations.
How it connects
Connects multibyte strings, wchar_t, mbsrtowcs, mbstate_t, locales, Unicode, and wcs-prefixed string functions.

Also explained in

Compare how 2 books explain wide character string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.