Using the casting you helped the compiler to find an error in this code snippet
int** pt;
pt = (int*) malloc(sizeof(int)*10);
For example the error message can look like
error: assignment from incompatible pointer type [-Werror=incompatible-pointer-types]
pt = (int*) malloc(sizeof(int)*10);
^
Without the casting the compiler could accept this evidently invalid code because the return type of the function malloc
is void *
and a pointer of the type void *
may be assigned to a pointer to object of any other type.
That is in the right side of the assignment the evaluated expression has the type int *
while in the left side of the assignment there is an object of the type int **
and there is no implicit conversion from the type int *
to the type int **
.
This code snippet
int** pt;
*pt = (int*) malloc(sizeof(int)*10);
is invalid by another reason. The pointer pt
is not initialized by a valid address of an object. It has either indeterminate value if the pointer has automatic storage duration or NULL if the pointer has static storage duration. In any case its dereferencing results in undefined behavior.
So it would be correctly to write
int* pt;
^^^^^^^
pt = (int*) malloc(sizeof(int)*10);
However this construction
int** pt;
//...
*pt = (int*) malloc(sizeof(int)*10);
can be made valid in some context.
Let's assume that you declared a pointer
int *pt;
and want to initialize it in a function. In this case you have to pass the pointer to the function by reference. Otherwise the function will deal with a copy of the pointer and in this case the original pointer will not be assigned in the function.
So the corresponding code snippet can look as it is shown in the demonstrative program
#include <stdlib.h>
#include <stdio.h>
size_t f( int **pt )
{
const size_t N = 10;
*pt = (int*) malloc( sizeof( int ) * N );
if ( *pt )
{
int value = 0;
for ( size_t i = 0; i < N; i++ ) ( *pt )[i] = value++;
}
return *pt == NULL ? 0 : N;
}
int main( void )
{
int *pt;
size_t n = f( &pt );
if ( n )
{
for ( size_t i = 0; i < n; i++ ) printf( "%d ", pt[i] );
putchar( '\n' );
}
free( pt );
}
The program output is
0 1 2 3 4 5 6 7 8 9