cpointersmalloctypecasting-operator

Type casting an array of pointers when using malloc


When I am running the following program it executes just fine:

int *a, i=3;
int **arr;
a = &i;
arr = malloc(sizeof(int*));
arr[0] = a;

However, malloc returns a void* pointer so it would be prettier to type cast it. I tried (int*)malloc(sizeof(int*)) but I am getting a warning:

assignment from incompatible pointer type

pointing at the line of typecasting (specifically at the equals sign). What is the correct type for the specific case? Thank you in advance!


Solution

  • The type should be the same as the pointer you're assigning to. Since you're assigning to int **arr, you should cast to int **.

    arr = (int **)malloc(sizeof(int*));
    

    However, it's generally not recommended to cast the result of malloc() in C. See Do I cast the result of malloc? for reasons.