Consider the following code snippet. What is the output?#include <stdio.h>int main() { int arr[4] = {10, 20, 30, 40}; int *p = &arr[1]; printf("%d\n", *(p + 2)); return 0;}
Question
Consider the following code snippet. What is the output?#include <stdio.h>int main() { int arr[4] = {10, 20, 30, 40}; int *p = &arr[1]; printf("%d\n", *(p + 2)); return 0;}
Solution
The output of the code will be 40.
Here's the step by step explanation:
-
An array
arrof 4 integers is declared and initialized with the values 10, 20, 30, 40. -
A pointer
pis declared and it is initialized to point to the second element of the array (i.e.,arr[1]which is 20). -
In the
printfstatement,*(p + 2)is used. This is pointer arithmetic, wherep + 2means the address of the third element afterp(includingp). Sincepis pointing toarr[1],p + 2will point toarr[3]. -
The
*operator is used to dereference the pointer, i.e., get the value stored at the address the pointer is pointing to. So,*(p + 2)will give the value stored atarr[3], which is 40.
So, the output of the code will be 40.
Similar Questions
What is the output for the following code?
What does the following code snippet do?
What is the output of the following code in Python?
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following C++ code?
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.