S
somenath
Please help me to verify my understanding about the output of the following program.
int main(void)
{
int (*p)[5] ,i ;
int a1[] = { 1,2,3,4,5 };
p = &a1;
printf("\nSize of int = %d\n",(int)sizeof(int));
printf("\nsizeof *p = %d\n",(int) sizeof(*p)); //2nd printf
for ( i =0;i < 5; i++ ) {
printf("address of *p + %d = %x \n",i , (*p +i )); //3rd printf
}
return 0;
}
The output is
+++++++++
Size of int = 4
sizeof *p = 20
address of *p + 0 = 28ac44
address of *p + 1 = 28ac48
address of *p + 2 = 28ac4c
address of *p + 3 = 28ac50
address of *p + 4 = 28ac54
The type of *p is array 5 of int in sizeof operator, as arr of 5 int is not getting converted to pointer to first element of arry 5 of int . That's the reason the output of 2nd printf is 5 *sizeof int.
Now in case of third printf , type of *p is actually pointer to the first element of arry of 5 int or in easier way type of
*p is now int* . That's the reason the difference between *p+1 and *p+ 0 is sizeof int* . In this case it is 4.
Please let me know if my understanding is correct.
int main(void)
{
int (*p)[5] ,i ;
int a1[] = { 1,2,3,4,5 };
p = &a1;
printf("\nSize of int = %d\n",(int)sizeof(int));
printf("\nsizeof *p = %d\n",(int) sizeof(*p)); //2nd printf
for ( i =0;i < 5; i++ ) {
printf("address of *p + %d = %x \n",i , (*p +i )); //3rd printf
}
return 0;
}
The output is
+++++++++
Size of int = 4
sizeof *p = 20
address of *p + 0 = 28ac44
address of *p + 1 = 28ac48
address of *p + 2 = 28ac4c
address of *p + 3 = 28ac50
address of *p + 4 = 28ac54
The type of *p is array 5 of int in sizeof operator, as arr of 5 int is not getting converted to pointer to first element of arry 5 of int . That's the reason the output of 2nd printf is 5 *sizeof int.
Now in case of third printf , type of *p is actually pointer to the first element of arry of 5 int or in easier way type of
*p is now int* . That's the reason the difference between *p+1 and *p+ 0 is sizeof int* . In this case it is 4.
Please let me know if my understanding is correct.