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
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;}
What is the output of the following code snippet?int x = 5;int y = 10;int *ptr = &x;*ptr = y;printf("%d", x);510015Generates a compilation error
What is the output of the following code?#include <stdio.h>int main() { int i = 0; for (; i < 5; i++); printf("%d ", i); return 0;}
What is the output of the following code?int arr[5] = {10, 20, 30, 40, 50};int *ptr = arr;cout << *(ptr + 2);10203040
What is the output of the following piece of code?int i;i = 10;while (i < 20){ printf("%d", i % 2); i++;}
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.