What is the output of the following program?
#include <stdio.h>
int main() {
double a[2]={20.0,25.0},* p,* q;
p=a ;
q=p+1 ;
printf("%d,%d", (int) (q-p),( int)(* q- * p));
return 0;} View worked solution
Answer: B
Let us trace the execution of the program step-by-step:
-
Array Initialization:
An array
aof twodoubleelements is initialized as:a[0] = 20.0anda[1] = 25.0 -
Pointer Assignments:
p = a;makesppoint to the first elementa[0].q = p + 1;makesqpoint to the next elementa[1].
-
Evaluating the Expressions in
printf:-
First Expression
(int)(q - p):
In C, pointer subtraction (q - p) yields the distance between the two pointers in terms of the number of elements of the base type (here,double), not the number of bytes. Sinceqpoints to index1andppoints to index0: Casting this tointgives1. -
Second Expression
(int)(*q - *p):
Dereferencing the pointers gives their respective values: Subtracting these values: Casting5.0tointgives5.
-
First Expression
Thus, the printf statement outputs 1,5, which corresponds to option B.
Free practice · Your answers on this page are not saved.
