Search code examples
c

Casting Pointer array from one type to another


Why is the following program not working?

void test(int*[]);
int main()
{
    char *a[2];
    test((int*[])a);
    
    return 0;
}

void test(int* c[]){

}

It shows

error cast to incomplete type 'int*[]' test((int*[])a)

The problem can be fixed by using:

test((int**)a);

But what is wrong with the previous code?

Edit: In the function prototype declaration, the same thing is used inside the parenthesis as the cast.

(int*[])

So why is that not an incomplete type?


Solution

  • The problem is that int *[] is an incomplete type which cannot be instantiated.

    In the function declaration, int *[] is exactly equivalent to int ** since the actual argument passed to the function will be a "pointer to pointer to int" in either case. Therefore, in the context of the function declaration, int *[] actually refers to a complete type (pointer to pointer to int).

    In the cast, however, (int *[])a tells the compiler to create a temporary of type int *[] and that is not allowed since it is an incomplete type.

    While we cannot have values of incomplete type, we can have pointers to such values, so the following compiles (just for the sake of the example; this is not a recommended construct) - a typedef is used for clearer notation:

    typedef int * incompleteIntArray[];
    
    void test(int*[]);
    int main()
    {
        char *a[2];
        test(*(incompleteIntArray *)&a);
    }
    

    The point here is that while incompleteIntArray (aka int *[]) is an incomplete type, a pointer to this type is not. Therefore, a pointer &a to char *[2] can be cast to a pointer to int *[] and we may dereference this to create the function argument. However, this only works because arrays are always passed by reference, so the actual argument is a pointer, not an instance of int *[].