In C, arrays of pointers and multi-level pointers: what substring is printed by this code? #include <stdio.h> int main() { static char *s[] = {"black", "white", "pink", "violet"}; char *ptr[] = {s + 3, s + 2, s + 1, s}, p; p = ptr; ++p; / now points to (s + 2) / printf("%s", p + 1); return 0; }

Difficulty: Medium

Correct Answer: ink

Explanation:


Introduction / Context:
This problem examines indexing through an array of char, then through an array of pointers to those pointers, and finally performing pointer arithmetic to print a substring. Understanding the types at each dereference level is essential.


Given Data / Assumptions:

  • s is an array: {"black", "white", "pink", "violet"} with indices 0..3.
  • ptr is an array of char: {s+3, s+2, s+1, s}.
  • p is a char used to walk through ptr.


Concept / Approach:
After p = ptr;, p is s+3. The pre-increment ++p advances to ptr[1] which is s+2. Dereference steps: p is s+2, **p is (s+2) which equals s[2] → the string literal "pink". Adding 1 to a char skips the first character and yields the substring starting at index 1.


Step-by-Step Solution:
After ++p, **p == s[2] == "pink".Compute **p + 1 → pointer to the substring of "pink" starting at index 1.The substring is "ink".printf prints "ink".


Verification / Alternative check:
Print **p first to confirm it is "pink"; then print **p + 1 to see the substring shift.


Why Other Options Are Wrong:
"ack", "ite", and "let" correspond to substrings from "black", "white", and "violet" respectively, not selected by the given pointer path.


Common Pitfalls:
Miscounting the pre-increment step or confusing which string index *p resolves to. Also, forgetting that + 1 on a char advances by one character.


Final Answer:
ink

More Questions from Pointers

Discussion & Comments

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