C mbtowc() function

C mbtowc() function - Convert a character to a wide-character code

Syntax mbtowc() function

int mbtowc(whcar_t *pwc, const char *str, size_t n)

The mbtowc() function is used to first determine the length of the multibyte character pointed to by string. As described in mbstowcs, the multibyte character is then converted into a wide character. A maximum of n bytes are examined.

Parameters mbtowc() function

Name Description Required /Optional
pwc Address of a wide character (type wchar_t). Required
str Address of a sequence of bytes (a multibyte character). Required
n Number of bytes to check. Required

Return value from mbtowc()

If string is NULL:

  • Nonzero when the active locale is mixed byte.
  • 0 otherwise.

If string is not NULL:

  • The number of bytes that make up the converted multibyte character.
  • 0 if string points to the null character.
  • -1 if string does not point to a valid multibyte character.

Example: mbtowc() function

The following example shows the usage of mbtowc() function.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h> 
#define LOCNAME "qsys.lib/mylib.lib/ja_jp959.locale"
/*Locale created from source JA_JP and CCSID 939 */
int length, temp;
char string [] = "\x0e\x41\x71\x0f\x41";
wchar_t text[6];
int main(void)
   /* initialize internal state variable */
   temp = mbtowc(text, NULL, 0);            
   setlocale(LC_ALL, LOCNAME);
   /* Set string to point to a multibyte character. */
   length = mblen(string, MB_CUR_MAX);
   temp = mbtowc(text,string,length);
   text[1] = L'\0';
   printf("Wide character string: %ls",text);


Wide character string: ♫

C Programming Code Editor:

Previous C Programming: C mbstowcs()
Next C Programming: C wcstombs()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Returning an array using C

You can't return arrays from functions in C. You also can't (shouldn't) do this:

char *returnArray(char array []){
 char returned [10];
 //methods to pull values from array, interpret them, and then create new array
 return &(returned[0]); //is this correct?

returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

Dynamically allocate the memory inside of the function (caller responsible for deallocating ret)

char *foo(int count) {
    char *ret = malloc(count);
        return NULL;

    for(int i = 0; i < count; ++i) 
        ret[i] = i;

    return ret;

Call it like so:

int main() {
    char *p = foo(10);
    if(p) {
        // do stuff with p

    return 0;

Ref : https://bit.ly/3yFIeao

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook