GATE CS 2024 Set 2 — Question 36

MCQ+2 / -0.67MediumPointers & Pointer ArithmeticC ProgrammingProgramming & Data StructuresArrays & Strings in C

Programming & Data Structures → C Programming → Arrays & Strings in C

Last updated

Question

What is the output of the following C program?
#include 
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

Correct answer

(B) 1,5

Solution

1.Pointer Arithmetic: The array a is initialized with two double values: a[0] = 20.0 and a[1] = 25.0. The pointer p is assigned the base address of the array (p = a), so it points to a[0]. The pointer q is assigned p + 1, so it points to the next element, a[1].
2.Pointer Subtraction: In C, when you subtract two pointers of the same type (q - p), the result is the number of elements of that type between the two addresses. Since q points to the element immediately following p, q - p is 11. Casting this to (int) gives 11.
3.Value Subtraction: *q dereferences to the value 25.025.0, and *p dereferences to 20.020.0. The expression *q - *p calculates the difference between these values: 25.020.0=5.025.0 - 20.0 = 5.0. Casting this result to (int) gives 55.
4.Final Output: The printf function uses the format string "%d,%d", resulting in the output 1,5.

More questions on C Programming

Practice GATE CS PYQs with adaptive difficulty

Timed practice, skill tracking, and AI explanations — free to start.

Start practicing free