What is the output of the following code?int arr[] = {1, 2, 3, 4, 5};int *p = arr;printf("%d\n", *(p + 2));
Question
What is the output of the following code?int arr[] = {1, 2, 3, 4, 5};int *p = arr;printf("%d\n", *(p + 2));
Solution
The output of the code will be 3.
Here's the step by step explanation:
-
An integer array
arr[]is declared and initialized with the values{1, 2, 3, 4, 5}. -
A pointer
*pis declared and it is pointed to the base address of the arrayarr[]. This meanspis pointing to the first element of the array, which is1. -
In the
printfstatement,*(p + 2)is used. This is pointer arithmetic. Here,pis incremented by2. Sincepis an integer pointer, incrementing it by2will make it point to the third element of the array (as in C, array indexing starts from0). -
So,
*(p + 2)will dereference the pointer and give the value at the third position of the array, which is3.
Hence, the output of the code will be 3.
Similar Questions
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;}
What is the output of the following code?int arr[] = {10, 20, 30, 40, 50};printf("%d\n", 2[arr]);
.What will be the output of the following C code?int main() {int arr[] = {1, 2, 3, 4, 5};printf("%d", arr[3]);return 0;}*1 point1234
What will be the output of the following code?12345678910111213141516#include<stdio.h>int main() { int arr[] = {2, 4, 6, 8, 10}; int *p = &arr[0]; for (int i = 1; i <= 4; i++) { if (i % 3 == 0) { p += 1; } } printf("%d", (*(p + 2))); return 0; }
What will be the output of the following code?#include <stdio.h>int main() { int arr[4] = {0, 1, 2, 3}; printf("%d\n", arr[-1]); return 0;}
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.