Knowee
Questions
Features
Study Tools

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));
🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the code will be 3.

Here's the step by step explanation:

  1. An integer array arr[] is declared and initialized with the values {1, 2, 3, 4, 5}.

  2. A pointer *p is declared and it is pointed to the base address of the array arr[]. This means p is pointing to the first element of the array, which is 1.

  3. In the printf statement, *(p + 2) is used. This is pointer arithmetic. Here, p is incremented by 2. Since p is an integer pointer, incrementing it by 2 will make it point to the third element of the array (as in C, array indexing starts from 0).

  4. So, *(p + 2) will dereference the pointer and give the value at the third position of the array, which is 3.

Hence, the output of the code will be 3.

This problem has been solved

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++;}

1/3

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.