What will the following code output?#include <stdio.h>int main() { int arr[3] = {1, 2, 3}; int *p = arr; printf("%d\n", *(p + 2)); return 0;}
Question
What will the following code output?#include <stdio.h>int main() { int arr[3] = {1, 2, 3}; int *p = arr; printf("%d\n", *(p + 2)); return 0;}
Solution
The code will output "3".
Here's the step-by-step explanation:
-
An integer array
arrof size 3 is declared and initialized with the values 1, 2, and 3. -
A pointer
pis declared and initialized to point to the first element of the arrayarr. -
The
printffunction is called to print the value of the element at the address(p + 2). In C, when you add an integer to a pointer, it advances by that many elements in the array. So,p + 2points to the third element of the arrayarr. -
*(p + 2)dereferences the pointer(p + 2), which means it gives the value stored at the address(p + 2). This is the third element of the arrayarr, which is 3. -
So, the output of the program is "3".
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.