Pointer–pointer arithmetic and precedence in C: Determine the outputs printed by this program (track each change exactly).\n#include<stdio.h>\n\nint main()\n{\n static int arr[] = {0, 1, 2, 3, 4};\n int *p[] = {arr, arr+1, arr+2, arr+3, arr+4};\n int **ptr = p;\n ptr++;\n printf("%d, %d, %d\n", ptr - p, *ptr - arr, **ptr);\n *ptr++;\n printf("%d, %d, %d\n", ptr - p, *ptr - arr, **ptr);\n *++ptr;\n printf("%d, %d, %d\n", ptr - p, *ptr - arr, **ptr);\n ++*ptr;\n printf("%d, %d, %d\n", ptr - p, *ptr - arr, **ptr);\n return 0;\n}

Difficulty: Medium

Correct Answer: 1, 1, 1 2, 2, 2 3, 3, 3 3, 4, 4

Explanation:


Introduction / Context:
This problem exercises operator precedence and pointer arithmetic with pointers to pointers. Understanding how ptr, ptr, and ptr change after each expression is essential.



Given Data / Assumptions:

  • arr = {0,1,2,3,4}.
  • p is an array of int pointing to each element of arr.
  • ptr is an int initially pointing at p[0].


Concept / Approach:
Key rules: postfix ++ has higher precedence than unary *; pointer arithmetic advances by element size; ptr - p yields the index. Expressions like *ptr++ mean *(ptr++) (increment ptr); *++ptr means *(++ptr) (increment first); ++*ptr increments the pointer stored at *ptr (i.e., p[index]) so the pointer itself moves to the next int.



Step-by-Step Solution:
After ptr++ → ptr points to p[1] =&arr[1] → prints 1, 1, 1.ptr++ → increment ptr to p[2] (dereferenced value discarded) → prints 2, 2, 2.++ptr → pre-increment ptr to p[3] → prints 3, 3, 3.++ptr → increments the int stored at p[3] from &arr[3] to &arr[4] → prints 3, 4, 4.



Verification / Alternative check:
Manually expand the addresses or add auxiliary prints showing pointer values before/after each operation.



Why Other Options Are Wrong:
They misinterpret precedence or the target of ++, giving wrong indices/values.



Common Pitfalls:
Reading *ptr++ as (*ptr)++ (which it is not); forgetting that ++*ptr modifies the pointed-to pointer, not the int value.



Final Answer:
1, 1, 1 2, 2, 2 3, 3, 3 3, 4, 4

More Questions from Arrays

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion