edited by
6,845 views
1 votes
1 votes
#include<stdio.h>
int main()
{
 int a[]={1,2,3,4,5,6};
 int *ptr=(int *)(&a+1);
 printf("%d",*(ptr-1));
 return 0;
}

this program print => 6 but if we try

#include<stdio.h>
int main()
{
 int a[]={1,2,3,4,5,6};
 int *ptr=(int *)(&a+2);
 printf("%d",*(ptr-2));
 return 0;
}

justify why this program not print => 6

edited by

1 Answer

1 votes
1 votes

 This question is about difference between $\left ( *a+1 \right )$ and $ ( $&$a+1 )$

If starting address of array is $1000$

1st one will print $1000+n\times size of (int)$$=1000+1\times 4=1004$

where as 2nd one will print $=1000+\text{size of elements in that row}$$=1000+6\times 4=1024$

Now, how ptr working

In 1st program , *(ptr-1) just printing one element back, where now ptr is pointing, i.e. 6

#include<stdio.h>
int main()
{
 int a[]={1,2,3,4,5,6};
 int *ptr=(int *)(&a+2);
 printf("%d",*(ptr-2));
 return 0;
}

In 2nd program 

int *ptr=(int *)(&a+2);

Here ptr pointing to

$=1000+\text{size of elements in that two rows}$$=1000+2\times6\times 4=1048$ as shown in diagram

Now, while printing it will point $*(ptr-2)=1048-(2\times 4)=1040$ which is also NULL

So, it will print nothing

https://gateoverflow.in/232228/array-and-pointer

Type of $arr$ is $int \ *$
While the type of $ \& arr$ is $int (*) [5].$

$\text {Array_name gives the address of}\ 1^{st} \ \text{element of the array. } $
$\text{&Array_name gives the address of whole array} $
 

edited by

Related questions

0 votes
0 votes
0 answers
1
shiva0 asked Jan 11, 2019
626 views
#include int main() { int i = 1; printf("%d %d %d\n", i++, i++, i); return 0; }
3 votes
3 votes
3 answers
2
Rudra Pratap asked Jul 20, 2018
1,761 views
#include <stdio.h int main() { static int i=5; if( i) { main(); printf("%d ",i); } }