Wide character conversion

romyd misc romydmisc@gmail.com
Thu Jun 8 13:29:00 GMT 2006


Hi All,

I'm new to gcc and i was trying to write a code to convert a char * to
wchar * and i found an example on
http://www.gnu.org/software/libc/manual/html_node/Converting-a-Character.html

Following is the code snippet

wchar_t * mbstouwcs (const char *s)
{
  size_t len = strlen (s);
//  wchar_t *result = malloc ((len + 1) * sizeof (wchar_t));
  wchar_t *result = (wchar_t *)calloc(16 * 2,'\0');
  wchar_t *wcp = result;
  wchar_t tmp;
  mbstate_t state;
  size_t nbytes;

  int i = 0;
// printf("Len%d\n",len);

  memset (&state, '\0', sizeof (state));
  while ((nbytes = mbrtowc (&tmp, s, len, &state)) > 0)
    {
      if (nbytes >= (size_t) -2)
        /* Invalid input string.  */
        return NULL;

//      printf("Counter%d\n",i);

        wprintf(L"Tmp%c",tmp);

//      *result++ = tmp;

//      printf("Counter%d\n",i);
        result[i] = tmp;
//      *result++;
        i++;



        len -= nbytes;
      s += nbytes;
    }

result[i] = '\0';
printf("Test\n");
wprintf(L"Size%d\n",sizeof(result));
wprintf(L"Result%s\n",result);
  return result;
}

When i try to print result, i only get the 1st character. Can any one
help me fixing this code, so it returns all the characters converted
to wchar in result. Please do send suggestions if anyone knows a
different way of converting a char * to wchar*.

Thanks,
Romy



More information about the Gcc-help mailing list