Consider the following code. What will be the output?#include <stdio.h>int main() { int arr[3] = {10, 20, 30}; int *p = arr; *(p + 1) = 40; printf("%d\n", arr[1]); return 0;}
Question
Consider the following code. What will be the output?#include <stdio.h>int main() { int arr[3] = {10, 20, 30}; int *p = arr; *(p + 1) = 40; printf("%d\n", arr[1]); return 0;}
Solution
The output will be 40.
Here's the step by step explanation:
-
An integer array
arrof size 3 is declared and initialized with the values 10, 20, and 30. -
A pointer
pis declared and initialized to point to the first element of the arrayarr. -
The statement
*(p + 1) = 40;changes the value of the second element in the arrayarrto 40. This is becausep + 1points to the second element of the array (since array indexing starts from 0), and*is used to dereference the pointer, i.e., access the value pointed by the pointer. -
The
printfstatement prints the value of the second element of the arrayarr, which is now 40.
So, the output of the program will be 40.
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.