C++ default argument as null pointer to a 2D array parameter and uninitialized storage: what will this program display?\n\n#include<iostream.h>\nclass CuriousTabArray\n{\n int array[3][3];\npublic:\n CuriousTabArray(int arr[3][3] = NULL)\n {\n if (arr != NULL)\n for (int i = 0; i < 3; i++)\n for (int j = 0; j < 3; j++)\n array[i][j] = i + j;\n }\n void Display(void)\n {\n for (int i = 0; i < 3; i++)\n for (int j = 0; j < 3; j++)\n cout << array[i][j] << " ";\n }\n};\nint main()\n{\n CuriousTabArray objBA; // uses default argument NULL\n objBA.Display();\n return 0;\n}

Difficulty: Medium

Correct Answer: The program will display 9 garbage values.

Explanation:


Introduction / Context:
This item explores default arguments, pointer conversion of array parameters, and uninitialized memory. The constructor accepts a parameter written as int arr[3][3], which actually decays to a pointer-to-array type; a default of NULL (zero pointer constant) is supplied. If no argument is passed, the body skips initialization, leaving the member array with indeterminate values.


Given Data / Assumptions:

  • Default argument NULL is used when objBA is created.
  • The if (arr != NULL) guard prevents any assignments.
  • array[3][3] is a non-static data member with no in-class initializer.


Concept / Approach:
In C++, built-in and POD members are not implicitly zero-initialized for automatic objects unless you explicitly do so. Because the constructor does nothing when arr == NULL, each element of array remains uninitialized (indeterminate). Streaming such values yields unspecified “garbage”.


Step-by-Step Solution:
1) Construct with default: arr == NULL. 2) Branch skips the initialization loop. 3) Display() iterates 9 elements and prints whatever bit patterns were in memory. 4) Therefore, nine garbage values appear separated by spaces.


Verification / Alternative check:
Pass a real array to the constructor to execute the loop and you would see the predictable sequence “0 1 2 1 2 3 2 3 4”.


Why Other Options Are Wrong:
Compilation is permitted; “NULL” is not printed literally; the specific numeric pattern (0..4) only appears if initialization runs.


Common Pitfalls:
Assuming members are zeroed automatically; misunderstanding default arguments with array parameters.


Final Answer:
The program will display 9 garbage values.

More Questions from Functions

Discussion & Comments

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