What does the following fragment of C-program print?
#include <stdio.h>
int main() {
char c[] = "2025-26";
char *p = c;
printf("%d", p[3] - p[1]);
return 0;
}
Explanation
Let's break down how the string is stored in memory and how the pointer indexing works:
1. Array Initialization and Memory Layout
The character array c is initialized with the string literal "2025-26". In C, character strings are 0-indexed and automatically end with a null terminator (\0).
The layout of the array elements in memory looks like this:
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
Character | '2' | '0' | '2' | '5' | '-' | '2' | '6' | '\0' |
2. Pointer Assignment
The statement char *p = c; assigns the base address of the array c to the pointer p. Therefore, p[i] is identical to c[i].
3. Evaluating the Expression
The expression inside the printf statement is:
Output=p[3]−p[1]
Output=’5’−’0’
When arithmetic operations (like subtraction) are performed on characters in C, their corresponding ASCII integer values are used:
Substituting these values into our equation:
Output=53−48=5