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
arr
of size 3 is declared and initialized with the values 1, 2, and 3. -
A pointer
p
is declared and initialized to point to the first element of the arrayarr
. -
The
printf
function 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 + 2
points 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".
Similar Questions
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?#include <stdio.h>int main() { int i; for (i = 0; i < 5; i++); printf("%d\n", i); return 0;}
What will be the output of the following Pseudocode?int c = 0, d = 0 while ( d< 6 ) d=d+2 c=c+1 end while loop print c3564
What will be the output of the following code snippet?var a = 1; var b = 0; while (a <= 3) { a++; b += a * 2; print(b); }*4 10 181 2 3None of Above1 4 7
What is the output of the following code snippet?int i = 0;do { if (i == 3) continue; System.out.print(i + " "); i++;} while (i < 5);
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.