arrayscpointerscastingincompatibility

What is difference in int* p and (int*) p in C


I couldn't understand use of (int*) p in following program for pointer to an array

#include<stdio.h>    
void main()     
{    
 int s[4][2];    
 int (*p)[2];    
 int i,j,*pint;    
    
 for(i=0;i<=3;i++)     
 {    
  p=&s[i];    
  pint=(int*)p; /*here*/    
  printf("\n");    
  for(j=0;j<=1;j++)    
  printf("%d",*(pint+j));    
 }    
}    

can i use *p instead of (int*) p here. thanks in advance


Solution

  • If you have an array declaration like this

    int s[4][2];
    

    then these three pointers have the same value

    int ( *p1 )[4][2] = &s;
    int ( *p2 )[2] = &s[0];
    int *p3 = &s[0][0]; 
    

    because all the pointers point to the initial address of the extent of memory allocated for the array.

    However the pointers have different types because they point to objects of different types.

    The first pointer points to the array in whole as a single object. the second pointer points to an array element that in turn has the array type int[2]. And the third array point to a scalar object of the type int.

    So you may not assign directly one pointer to another because they are incompatible though as it was mentioned they have the same value (address).

    You need to cast one pointer type to another pointer type explicitly.

    This assignment in the original program

    p=&s[i];
    

    assigns the address of each element (array of the type int[2]) to the pointer. In fact it is the address of the first element of the array that is it is equal to &s[i][0]. However the first expression and the last expression have different pointer types.

    So you need to use casting in this assignment

    pint=(int*)p;
    

    Now using the pointer arithmetic in this expression

    *(pint+j)
    

    you can traverse all scalar elements of the array initially pointed to by the pointer p.

    Pay attention to that this declaration of main

    void main() 
    

    is nit a standard declaration.

    You should declare the function main like

    int main( void )