Possible Duplicate:
Allocate memory for 2D array with minimum number of malloc calls
As far my knowledge of concern in C void pointer is automatically converted into appropriated data type. Below is the program in which I found the warning:
initialization from incompatible pointer type [enabled by default]
#define ROW 3
#define COL 2
int main()
{
void **ptr = malloc( ROW*COL* sizeof(int) );
int (*p)[COL] = ptr;
int i, j;
for( i = 0; i < ROW; ++i )
for( j = 0; j < COL; ++j )
scanf("%d", &p[i][j]);
for( i = 0; i < ROW; ++i )
{
for( j = 0; j < COL; ++j )
printf("%d ", p[i][j]);
printf("\n");
}
free(ptr);
return 0;
}
but it worked perfectly. If void** pointer is type casted into a “pointer to a COL size integer array” then it’s behavior should change and behave like 2D array?
Firstly,
void **pointer is not avoid *pointer.void **andvoid *are two completely different types. Whatever conversion properties apply tovoid *don’t apply to yourptr. Your initialization is indeed invalid, as compiler told you in the warning message.Secondly, there’s absolutely no need for a
void **pointer in your program. Where did it come form anyway? If you wanted to have an “intermediate” pointerptrin your program, you should have declared it withvoid *typeand the warning would disappear. However, as I said in my previous answer, there’s no real need for any intermediate pointer in this case. You can just do