What is the output of the following code?int arr[] = {1, 2, 3, 4, 5};int *p = arr;p++;printf("%d\n", *p);
Question
What is the output of the following code?
int arr[] = {1, 2, 3, 4, 5};
int *p = arr;
p++;
printf("%d\n", *p);
Solution
The output of the code will be 2.
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 to an integer
*p
is declared and it is initialized to point to the first element of the arrayarr[]
. So,*p
is pointing to the value1
. -
The pointer
p
is incremented by one usingp++
. This means that the pointer now points to the next element in the array, which is2
. -
The value of the element pointed to by
p
is printed usingprintf("%d\n", *p);
. Sincep
is pointing to the second element of the array,2
is printed.
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.