title: How to Convert UTF-16 to UTF-32 and Print the Resulting wchar_t in C?
body: <p>i'm trying to print out a string of UTF-16 characters. i posted this question a while back and the advice given was to convert to UTF-32 using iconv and print it as a string of wchar_t.</p>
  
  <p>i've done some research, and managed to code the following:</p>
  
  <pre><code>// *c is the pointer to the characters (UTF-16) i'm trying to print
  // sz is the size in bytes of the input i'm trying to print
  
  iconv_t icv;
  char in_buf[sz];
  char* in;
  size_t in_sz;
  char out_buf[sz * 2];
  char* out;
  size_t out_sz;
  
  icv = iconv_open("UTF-32", "UTF-16");
  
  memcpy(in_buf, c, sz);
  
  in = in_buf;
  in_sz = sz;
  out = out_buf;
  out_sz = sz * 2;
  
  size_t ret = iconv(icv, &amp;in, &amp;in_sz, &amp;out, &amp;out_sz);
  printf("ret = %d\n", ret);
  printf("*** %ls ***\n", ((wchar_t*) out_buf));
  </code></pre>
  
  <p>The iconv call always return 0, so i guess conversion should be OK?</p>
  
  <p>However, printing seems to be hit and miss. At times the converted wchar_t string prints OK. Other times, it seems to hit problem while printing the wchar_t, and terminates the printf function call altogether such that even the trailing "***" does not get printed.</p>
  
  <p>i also tried using</p>
  
  <pre><code>wprintf(((wchar_t*) "*** %ls ***\n"), out_buf));
  </code></pre>
  
  <p>but nothing ever gets printed.</p>
  
  <p>Am i missing something here?</p>
  
  <p>Reference: <a href="https://stackoverflow.com/questions/8315686/how-to-print-utf-16-characters-in-c">How to Print UTF-16 Characters in C?</a></p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>incorporated some of the suggestions in the comments.</p>
  
  <p>updated code:</p>
  
  <pre><code>// *c is the pointer to the characters (UTF-16) i'm trying to print
  // sz is the size in bytes of the input i'm trying to print
  
  iconv_t icv;
  char in_buf[sz];
  char* in;
  size_t in_sz;
  wchar_t out_buf[sz / 2];
  char* out;
  size_t out_sz;
  
  icv = iconv_open("UTF-32", "UTF-16");
  
  memcpy(in_buf, c, sz);
  
  in = in_buf;
  in_sz = sz;
  out = (char*) out_buf;
  out_sz = sz * 2;
  
  size_t ret = iconv(icv, &amp;in, &amp;in_sz, &amp;out, &amp;out_sz);
  printf("ret = %d\n", ret);
  printf("*** %ls ***\n", out_buf);
  wprintf(L"*** %ls ***\n", out_buf);
  </code></pre>
  
  <p>still the same result, not all the UTF-16 strings get printed (both the printf and the wprintf).</p>
  
  <p>what else could i be missing?</p>
  
  <p>btw, i'm using Linux, and have verified that wchar_t is 4 bytes.</p>