Question:

What is the output of the following C program? \begin{verbatim} #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; } \end{verbatim}

Show Hint

Pointer arithmetic on arrays calculates the difference in element positions, while dereferencing pointers gives the actual value stored in the array.
Updated On: Jan 23, 2025
  • 4, 8
  • 1, 5
  • 8, 5
  • 1, 8
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is B

Solution and Explanation

The program initializes an array \(a[2] = \{20.0, 25.0\}\), two pointers \(p\) and \(q\), and performs the following steps:
1. \(p = a\): Pointer \(p\) now points to the first element of the array, i.e., \(a[0] = 20.0\).
2. \(q = p + 1\): Pointer \(q\) now points to the second element of the array, i.e., \(a[1] = 25.0\).
3. The statement \texttt{q - p} calculates the difference in pointer positions. Since \(q\) points to the second element and \(p\) points to the first element, \(q - p = 1\).
4. The statement \texttt{*q - *p} calculates the difference between the values pointed to by \(q\) and \(p\). This gives: \[ *q - *p = a[1] - a[0] = 25.0 - 20.0 = 5.0. \] 5. The \texttt{printf} statement prints these values as integers: \[ \text{Output: } (int)(q - p) = 1, \quad (int)(*q - *p) = 5. \] Final Answer: \[ \boxed{\text{(B)}} \]
Was this answer helpful?
0
0

Questions Asked in GATE CS exam

View More Questions