Search code examples
cimplicit-conversionvoid-pointerspointer-arithmetic

Array type casting in C


I have a program as given below, and I am learning type casting in C. Here I am trying to cast void* into int*. But the compiler is throwing an error saying "error: operand of type 'void' where arithmetic or pointer type is required - printf("%d\n",(int *)(a[2]));"

Appreciate your help to do this type casting.

#include <stdio.h>

void printArray(void* a){
        printf("%d\n",(int *)(a[2]));

}

int main(){
        int a[] = {1,2,3,4};
        printArray(a);
        return 0;
}

Solution

  • a[2] is equivalent to *(a + 2). a is a void *, so you are dereferencing a void * which is ilegal.

    You should cast a to int * and then dereference it, like so:

    *((int *)a + 2)