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;
}- (A)
4,8
- (B)
1,5
- (C)
8,5
- (D)
1,8
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;
}4,8
1,5
8,5
1,8
ANSWER
The output of the program is 1,5 — option B.
Official answer: BSource: Official answer key, GATE 2024 CS2 (IISc Bengaluru)
double a[2] = {20.0, 25.0} declares an array of 2 doubles: a[0]=20.0, a[1]=25.0.
p = a; — array-to-pointer decay makes p point to a[0] (value 20.0).
q = p + 1; — pointer arithmetic on a double* advances by one element (the compiler scales by sizeof(double)), so q points to a[1] (value 25.0).
q - p is pointer subtraction between two pointers of the same type, which the language defines to yield the number of elements between them, i.e. the byte difference divided by sizeof(double). Here that is 1, regardless of sizeof(double) being 8. (int)(q - p) = 1.
*q - *p = 25.0 - 20.0 = 5.0; (int)(5.0) = 5.
The printf("%d,%d", ...) therefore prints 1,5, matching option B.
KEY IDEA
Subtracting two pointers of the same type gives the number of array elements between them (the language defines it as the byte difference divided by the element's sizeof), not a raw byte offset — this is different from ordinary pointer-to-integer or byte-address reasoning.
WATCH OUT FOR
Assuming q - p returns the byte offset (sizeof(double) = 8) rather than the element count (1), which leads to wrongly picking option A (4,8) or C (8,5).
From the GATE 2024 CS2 paper. Every question of this paper · Download the full paper · All 11 Pointers & arrays questions, with notes