Question:

Consider the following code:

int a;
int arr[] = {30, 50, 10};
int *ptr = arr[10] + 1;
a = *ptr;
(*ptr)++;
ptr = ptr + 1;
printf("%d", a + arr[1] + *ptr);
  

Show Hint

When working with pointers in C, be careful of accessing elements out of bounds, as this can lead to undefined behavior. Always ensure that pointers are within the bounds of the array.
Updated On: Feb 20, 2025
  • 100
  • 110
  • 111
  • 120
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is C

Solution and Explanation

Step 1: Understanding the code.

- We are given an array \( arr[] = \{30, 50, 10\} \).
- \( ptr \) is initialized to point to \( arr[10] + 1 \), which points to a memory location after the end of the array.
- \( a = *ptr \) assigns the value at the memory location pointed by \( ptr \) to \( a \).


Step 2: Evaluating the operations.

- Initially, \( ptr \) points beyond the bounds of the array. This is undefined behavior in C, and \( *ptr \) could return an arbitrary value. However, assuming it's accessing a valid memory location, the next steps depend on it.
- The line \( (*ptr)++ \) increments the value at \( ptr \) by 1.
- The pointer is then moved one step forward with \( ptr = ptr + 1 \).


After these operations:
- \( a \) will hold the value of \( *ptr \) (the value before it was incremented).
- \( a + arr[1] + *ptr \) gives \( a + 50 + \text{updated value at } ptr \).


Thus, the output of the program is 111.
Was this answer helpful?
0
1