Home > Software design >  Type casting an array of pointers when using malloc
Type casting an array of pointers when using malloc

Time:11-13

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!

CodePudding user response:

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.

CodePudding user response:

You should use int**, not int* because the type of arr is int**.

Note that the better pattern for an allocation is:

arr = malloc(sizeof *arr);

It is robust to changes of arr type. Moreover it is compact and it avoids repetition. It will automatically detect if arr is changed to an array or a non-ponter. The size of an allocation is adjusted automatically as well.

The main problem with malloc is not the return type but assuring that the correct number of bytes is allocated.

CodePudding user response:

In general if you are allocating an object of the type T then the returned pointer of a call of malloc should be casted to the type T *.

For example

T *p = ( T * )malloc( sizeof( T ) );

That is you want to obtain a pointer to an object of the type T, So the obtained pointer will have the type T *.

If the object has for example the type int * then the corresponding pointer will have the type int **.

IN C a pointer to the type void may be assigned to a pointer of any other type without casting. Sometimes casting in C is used for self-documenting or to avoid some kinds of errors.

  • Related