Q71.Marks: +2.0UGC NET Paper 2: Computer Sc 23rd August 2024 Shift 1
#include < stdio. h >
void main()
{
int arr[] = {1, 2, 3, 4, 5};
int *p = arr;
printf("%d", *p++);
printf("%d", *(p + 1));
}
Find the output of the above code?
1.1, 2
2.1, 3✓ Correct
3.2, 3
4.1, 4
Solution
The correct answer is 1, 3
Concept:
Understanding *p++:
This is a combination of dereferencing and post-increment. First, the value pointed to by `p` is used, and then `p` is incremented. This means that the initial value pointed to by `p` (which is `arr[0]` or `1`) is used in the expression, and then `p` is incremented to point to the next element of the array (`arr[1]`).
Understanding *(p + 1):
This expression adds 1 to the pointer `p`, but does not change the value of `p`. Instead, it returns the address of the element that is one position ahead of the current element pointed to by `p`. Therefore, `p + 1` points to `arr[2]` after the increment operation in Line 1.
Explanation:
Let's break down the code step by step:
Step 1:
Initially, `arr` is an array with elements `{1, 2, 3, 4, 5}` and `p` is a pointer pointing to the first element of the array, i.e., `arr[0]`.
Line 1:
`printf("%d", *p++);`
Here, `*p` gives the value at `p`, which is `1` (the first element of the array). Then `p` is incremented to point to the next element of the array (`arr[1]`). Therefore, the output of this line is `1`.
Step 2:
After Line 1, `p` now points to `arr[1]` (which is `2`).
Line 2:
`printf("%d", *(p + 1));`
Here, `p + 1` points to `arr[2]` (since `p` is currently pointing to `arr[1]`). Therefore, `*(p + 1)` gives the value at `arr[2]`, which is `3`. Therefore, the output of this line is `3`.
Hence the correct answer is:
The output of the above code is 1, 3.