What is wcstombs() in C?

We can use the wcstombs() function to convert a wide-character string to its equivalent multibyte sequence of characters. We can do this until we convert the maximum number of bytes or encounter a NULL character.

Library

The wcstombs() function is defined in the following library:

#include<stdlib.h>

Declaration

Below is the declaration of the wcstombs() function:

size_t wcstombs (char* destination, const wchar_t* source, size_t maximum);

Parameters

  • destination: The pointer to a char array at least maximum bytes long.
  • source: The pointer to the wide-character string that will be translated.
  • maximum: An unsigned integral thst specifies the maximum number of bytes that will be translated.

Return value

Upon successful conversion, the function returns the number of bytes written into destination, excluding the null character. In case of any error, the function returns -1.

Code

The code below explains the use of wcstombs() function.

#include <stdio.h>
#include <stdlib.h>
int main() {
wchar_t src[] = L"I love Educative <3";
char dest[64];
int returnValue;
returnValue = wcstombs(dest, src, sizeof(dest));
printf("Wide-character string: %ls\n", src);
printf("Multibyte string: %s\n", dest);
printf("Number of bytes converted: %d\n", returnValue);
return 0;
}

Explanation

In line 5-7, a wide-character string is initialized and a character string and an integer are declared. Then, in line 9, the function is called with the necessary parameters. The subsequent lines show the output.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved