-4

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
UV0
  • 13
  • 6

2 Answers2

0

In your code,

 pint=(int*)p;

p is of type int (*)[2], i.e., pointer to an array of 2 ints, and pint is a int *. They are not compatible types, so you need the cast.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • But even if i dont cast and use pint=*p it gives same output how that so – UV0 Sep 18 '20 at 05:49
  • @UV0 In this instance, using `*p` effectively does the same thing. It dereferences the pointer, resulting in an `int [2]` value which decays to `int *` when assigned to `pint`. Note that the dereference doesn't actually perform a memory reference in this case. It merely changes the type. A second dereference *would* cause a memory reference to be performed. – Tom Karzes Sep 18 '20 at 06:22
0

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 )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335