Array indexing into a string literal in C: what character does this code print? #include<stdio.h> #include<string.h> int main() { printf("%c ", "abcdefgh"[4]); return 0; } Pick the exact character output.

Difficulty: Easy

Correct Answer: e

Explanation:


Introduction / Context:
This item checks understanding that string literals can be indexed like arrays of char. The expression "abcdefgh"[n] yields the character at zero-based index n of the literal.



Given Data / Assumptions:

  • Literal is "abcdefgh".
  • Index used is 4 (zero-based).
  • printf with %c prints a single character.


Concept / Approach:
In C, a string literal has type array of const char (or char in older C), and it can be indexed before array-to-pointer decay in expressions. Zero-based indexing means position 0 is 'a', 1 is 'b', 2 is 'c', 3 is 'd', 4 is 'e'.



Step-by-Step Solution:
Compute index 4 → the 5th character in "abcdefgh".Character at index 4 is 'e'.printf("%c\n", ... ) prints that character followed by newline.



Verification / Alternative check:
You can confirm by printing the entire literal and manually counting or by looping indices 0..7 and printing each index and character.



Why Other Options Are Wrong:
'd': off by one (index 3).'abcdefgh': would require %s and a pointer to the first character.Error / None of the above: The code is valid and the correct character is 'e'.



Common Pitfalls:
Forgetting zero-based indexing; confusing %c and %s; assuming literals cannot be indexed.



Final Answer:
e

More Questions from Strings

Discussion & Comments

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