In C pointer arithmetic on arrays: what is printed when the function advances a char* pointer over an initialized array? #include int main() { void fun(char*); char a[100]; a[0] = 'A'; a[1] = 'B'; a[2] = 'C'; a[3] = 'D'; fun(&a[0]); return 0; } void fun(char *a) { a++; printf("%c", a); a++; printf("%c", a); }

C++ Programming Functions Difficulty: Easy
Choose an option
  • A
    AB
  • B
    BC
  • C
    CD
  • D
    No output
  • E
    AD

Answer

Correct Answer: BC

Explanation

Introduction / Context:This problem checks pointer arithmetic with character arrays. Incrementing a char moves to the next character. The code displays two successive characters after a starting position passed by the caller.

Given Data / Assumptions:

  • Array a[] has at least four initialized characters: A, B, C, D.
  • fun receives &a[0], the address of the first element.
  • Pointer increments occur twice before each print.

Concept / Approach:For char, a++ advances to the next element (next character). The first increment moves from A to B; the second increment moves from B to C. Printing *a after each step reveals those elements.

Step-by-Step Solution:Start: a points to a[0] = 'A'.a++ → points to a[1] = 'B'; print 'B'.a++ → points to a[2] = 'C'; print 'C'.Concatenated output: "BC".

Verification / Alternative check:Replace prints with indices to confirm the sequence of positions: 1 then 2, corresponding to B then C.

Why Other Options Are Wrong:"AB" would require printing before increment; "CD" would require starting at C; "No output" is false because printf is executed.

Common Pitfalls:Forgetting that the first print happens after one increment, not at the initial element.

Final Answer:BC

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