Q89.Marks: +2.0UGC NET Paper 2: Computer Sc 23rd August 2024 Shift 1
What will be the output of the following C code?
#include < stdio. h >
void main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *p = (int*) (&arr + 1);
printf("%d %d", *(arr + 1), *(p - 1));
}
1.10 50
2.20 50✓ Correct
3.30 40
4.20 40
Solution
The correct answer is 20 50
Concept:
In C, the array `arr` is a contiguous block of memory. When we use the expression `&arr + 1`, it points to the address just past the end of the array. By casting this to an integer pointer and subtracting one, we get the address of the last element of the array.
1. `int arr[5] = {10, 20, 30, 40, 50};` initializes an array of 5 integers.
2. `int *p = (int*) (&arr + 1);` - `&arr` gives the address of the entire array `arr`. - `&arr + 1` points to the memory address just past the end of the array. - Casting this to `(int*)` and then subtracting one gets us the address of the last element in the array.
3. `printf("%d %d", *(arr + 1), *(p - 1));` - `*(arr + 1)` fetches the value at the index `1` of the array, which is `20`. - `*(p - 1)` fetches the value just before the address `p`, which is the last element of the array, `50`.