CPA-21-02 practice question 24 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; void fun(char*); int main() { char t[4]={'0', '1', '2', '3'}; fun(&t[2]); return 0; } void fun(char *a) { cout

Full set: 257 questions
Answer options
A: It prints: 2 Correct answer
B: It prints: 21
C: It prints: 00
D: It prints: 02
Correct Answer:
A. It prints: 2
Explanation

The program initializes a character array t with four elements: '0', '1', '2', and '3'. The expression &t[2] computes the memory address of the third element in the array, which holds the character '2'. This address is passed to the function fun, which takes a character pointer a. Inside fun, the pointer a is dereferenced using the operator (a), which accesses the value stored at that memory address. The value is '2', which is then printed to the standard output.

Why Incorrect

B. Incorrect because the function only prints the single character pointed to by a, not a sequence.
C. Incorrect because the pointer points to t[2] ('2'), not t[0] ('0').
D. Incorrect because only the dereferenced value of t[2] is printed, without any preceding characters.

References

1. ISO/IEC 14882:2017, Programming Languages — C++, Section 8.3.1 [expr.unary.op], Paragraph 1 (Unary operators, dereference).

2. ISO/IEC 14882:2017, Programming Languages — C++, Section 11.3.4 [dcl.array], Paragraph 1 (Arrays).

3. Stroustrup, B. (2013). The C++ Programming Language (4th ed.). Addison-Wesley Professional. Chapter 7.3 (Pointers and Arrays).

Scroll to Top