779 views
12 votes
12 votes

What will be the output of the following C program?

#include <stdio.h>
int main()
{
    int a[10][20][30]={0};
    printf("%d %d %d",&a+1 - &a, 
       a[10][20] - a[10][10], a[10] - a[5]);
    return 0;
}
  1. 1 300 100
  2. 600 300 100
  3. 1 100 5
  4. None of the above

2 Answers

Best answer
22 votes
22 votes
    #include <stdio.h>
    int main()
    {
        int a[10][20][30]={0};
        printf("%d %d %d",&a+1 - &a, 
           a[10][20] - a[10][10], a[10] - a[5]);
        return 0;
    }

Output : 1,300,100

Let BA=1000 & Size of each element=1 and not 2 for simplicity.

$\&a+1-\&a$

$1000+1*(sizeof(a))-1000$

$1000+1*6000-1000$

$7000-1000$

$6000$

Now divide by 3-d array size

$\frac{6000}{6000}=1$


$a[10[20]-a[10][10]$

$*(*(a+10)+20)-*(*(a+10)+10)$

$(1000+10*20*30+20*30)-(1000+10*20*30+10*30)$

$7600-7300$

$300$

Now divide by element size

$\frac{300}{1}=300$


$a[10]-a[5]$

$*(a+10)-*(a+5)$

$(1000+10*20*30)-(1000+5*20*30)$

$7000-4000$

$3000$

Now divide by row size

$\frac{3000}{30}=100$

selected by
13 votes
13 votes

When $p_1$ and $p_2$ are two pointers pointing to same type, $p_1-p_2 = \dfrac{\text{integer value of }p_1 - \text{integer value of }p_2}{\text{sizeof}(*p_1)}$

&a+1 - &a  

  • p1 = &a+1 = address of a + 1*sizeof(a).
  • p2 = address of a
  • So, p1 - p2 = 1*sizeof(a) / sizeof(a) = 1.

a[10][20] - a[10][10]

  • p1 = a[10][20], point to int[30]
  • *p1 = int  
  • p2 = a[10][10]
  • So, p1 - p2 = ([a + 10*20*30*sizeof(int) ]- [a + 9*20*30*sizeof(int) + 10 * 30 * sizeof(int)  ]) / (sizeof(int)) = 600-300 = 300

a[10] - a[5])

  • p1 = a[10]
  • *p1 = int[30] (p1 is 2D array int[20][30])
  • p2 = a[5]
  • So, p1 - p2 = ([a + 10*20*30*sizeof(int) ]- [a + 5*20*30*sizeof(int) ]) / (30 * sizeof(int)) = 100
edited by
Answer:

Related questions

9 votes
9 votes
1 answer
2
gatecse asked Jul 26, 2020
640 views
What will be the output of the following C program:#include<stdio.h int main() { char* disease = "COVID-19"; (*disease)++; printf("%s",disease); }DPWJE-$20$DOVID-$19$COVI...