Question

I've having trouble working with the search.h library, you see, the attribute "key" of the ENTRY struct is of type char, but I need to work with wchar_t :

I have the following code:

/* search for the word in the dictionary and return the last one created */
static ENTRY *find(wchar_t *word) {
    ENTRY e;
    wcstombs(e.key, word, wcslen(word)+1); /* casting */
    /* e.key = (char)word; */
    return hsearch(e, FIND);
}

wchar_t *max_word = NULL;
int i, max_size = 0;
ENTRY *e;
e = find(array[i]); 
if (e && ((int) e->data > max_size)) {
   max_size = (int) e->data;
   max_word = e->key;
}

I don't know where the bug is, but I keep on receiving "segmentation violation" errors precisely in the code above.

So how can I get the search.h library to work properly with wchar_t types, and get the code I presented to function?

Was it helpful?

Solution

wcstombs doesn't magically allocate space in the ENTRY structure's key field; you have to do that yourself:

ENTRY e;
size_t len = wcslen(word);
size_t nbytes = wcstombs(NULL, word, 0) + 1;
e.key = malloc(nbytes);
// check for errors
wcstombs(e.key, word, nbytes);

Don't forget to free afterwards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top