edited by
741 views
4 votes
4 votes

State the output in below code snippet :

#include <stdio.h>
int main(void)
{
    char x[5] = { 1, 2, 3, 4, 5 };
    char *ptr = (char*)(&x + 1);
    printf("%d %d\n", *(x + 1), *(ptr - 1));
    return 0;
}
  1. Compile Error
  2. $2 \ 1$
  3. $2 \ 5$
  4. $3 \ 4$
edited by

2 Answers

Best answer
13 votes
13 votes

Here x[5] = { 1, 2, 3, 4, 5 };  means array x have 5 elements where 4th element is 5

now *ptr = (char*)(&x + 1)  //  
in (&x+1) ---> &x is the address of the ARRAY x. so (&x +1 ) adds the SIZE OF ARRAY x to &x. Which means it points to the location after the last element of x.

So ptr also points to that location.

Now , for this line *(x + 1), *(ptr - 1) ; // 

*(x + 1) = 2 because x is the array and point to starting element of the array which is oth element , means 1. So x+1 = 2 which is 1st element of the array x . It prints 2 .

ptr is of type (char*). So (ptr-1) subtracts sizeof(char) from ptr. Hence (ptr-1) is the address of the last integer (which is 5)in the array. So *(ptr-1) is 5.

The minimum size for char is 8 bits or 1 byte . 

That's why *(ptr - 1) points to 4th element of the array which is 5 and printing 5 .

The answer is 2,5 option C .

2 votes
2 votes
how does here *(ptr - 1) printing "5" not getting
Answer:

Related questions

3 votes
3 votes
1 answer
1
Bikram asked May 14, 2017
392 views
Assume that $a[4]$ is a one-dimensional array of $4$ elements, $p$ is a pointer variable and $p = a$ is performed. Now, which among these expressions is illegal?$p == a[0...
0 votes
0 votes
1 answer
2
Bikram asked May 14, 2017
351 views
Spot the error(s) in this code snippet :int n=2; // Line 1 switch(n) { case 1.5: printf( "gate"); break; case 2: printf( "overflow"); break; case 'A': printf("gateoverflo...
0 votes
0 votes
1 answer
3
Bikram asked May 14, 2017
199 views
#include<stdio.h int K = 10; int main() { foo(); foo(); return 0; } int foo() { static int k= 1; printf("%d ",k); k++; return 0; }What is the output of the above code sni...
0 votes
0 votes
1 answer
4
Bikram asked May 14, 2017
202 views
What is the output of the following program? int fun (int z) { if( z==0 || z==1 ) return 1; else return fun(z-1) ; } int main() { int y; y=fun(8); printf(“%d”...