Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression must be a pointer to a complete object type when cast void pointer

Tags:

c

I'm trying to do function remove extension of a name is type wchar_t or char, inside for() i cast void pointer to type wchar_t or char, then there was an error:

Expression must be a pointer to a complete object type.

Here is sample code to show an instance of the issue by itself.

int RemoveExtension(
    void    *p_str,     /*  Name                        */
    bool    isWchar     /*  true:wchar_t, false:char */
) {
    int ii, len;

    // Get length
    len = (isWchar) ? wcslen( (wchar_t *)p_str ) : strlen( (char *)p_str );

    // Remove extension
    /* wchar_t */
    if( isWchar ) {

        for( ii = 0; ii < len; ii++ ) {
            if( L'.' == (wchar_t *)p_str[ii] ) {  //Error here
                (wchar_t *)p_str[ii] = L'\0';     //Error here
                break;
            }
        }
    }
    /* char */
    else {

        for( ii = 0; ii < len; ii++ ) {
            if( '.' == (char *)p_str[ii]) {       //Error here
                (char *)p_str[ii] = '\0';         //Error here
                break;
            }
        }
    }

    return 0;
}

I'm not understanding what this error is trying to say. There is no object or struct here.

like image 276
Oosutsuke Avatar asked Sep 22 '26 02:09

Oosutsuke


2 Answers

To understand the error message, you have to know two things:

  1. Any value having a type stored somewhere is called an object in C. Your variables identify objects, your pointers (should) point to objects.
  2. Types in C can be complete or incomplete. The distinction is that for complete types, the size of an object of that type is known. For incomplete types, it is unknown. Without knowing the size, e.g. indexing isn't possible because you need the size to calculate the offset of the next array element. void is a special case of an incomplete type: it can't ever be completed, because it's unknown (void * is the generic pointer type and may point to an object of any type).

So, your compiler just tells you that p_str[ii] is invalid because you attempt to index on a pointer of type void *.


The source of the problem is simple: indexing has a higher precedence than casting, therefore just use parantheses to solve this problem:

((wchar_t *)p_str)[ii]

I dont know why you get exactly that error, but according to this table expression

(wchar_t *)p_str[ii] is (wchar_t *)(p_str[ii])

not ((wchar_t *)p_str)[ii],

probably it's not what you want

like image 25
Yet Another John Smith Avatar answered Sep 23 '26 16:09

Yet Another John Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!