Search code examples
arrayscwchar-t

convert wchar_t array into int array in C


I'm trying to convert a wchar_t array into an int array which contains the encoding of each wchar_t element in C. I know I can do this by a loop like the code below, is there any other way without using a loop which can greatly improve performance?

 for(int i=0; i< filesize; i++){
    t[i] = (int)p[i];   //t is an int array, p is a wchar_t array
}

Solution

  • Assuming wchar_t and int have the same size, memcpy is probably what you want.

    #include <string.h>
    #include <wchar.h>
    
    int main(void)
    {
        _Static_assert(sizeof (int) == sizeof (wchar_t), "This won't work");
        wchar_t warr[3] = {L'a', L'b', L'c'};
        int iarr[3] = {0};
        memcpy(iarr, warr, sizeof warr);
        // iarr now holds the same contents as warr
    }