Question

What is the output of the following C 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;}
Choose one option
Official answer and solution
Official answer
B
From
Official GATE 2024 answer key

Solution

Use C pointer arithmetic rules: subtracting two pointers to elements of the same array yields the index difference (not byte difference).

  1. p = a points to a[0] (20.0), and q = p + 1 points to a[1] (25.0).
  2. In C, subtracting two pointers of the same type (q - p) returns the number of array elements between them (scaled by sizeof(double)), so (int)(q - p) = 1.
  3. Dereferencing gives *q - *p = 25.0 - 20.0 = 5.0, so (int)(*q - *p) = 5.

Thus printf outputs 1,5.

Final answer

Option (B)

Common trap

Multiplying q - p by sizeof(double) = 8 to get 8,5.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2024 Computer Science and Information Technology - Set 2 (CS2)
Question
36 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.