C++ pointer size vs. string contents: what does this program actually print when taking sizeof on a char* variable (legacy headers)?\n\n#include<iostream.h>\n#include<string.h>\n#include<malloc.h>\nclass CuriousTabString{\n char txtName[20];\npublic:\n CuriousTabString(char txtTemp=NULL){ if(txtTemp!=NULL) strcpy(txtName, txtTemp); }\n void Display(){ cout << txtName; }\n};\nint main(){ char txtName=(char)malloc(10); strcpy(txtName, "CuriousTab"); txtName = 48; // overwrite first char\n CuriousTabString objTemp(txtName); cout << sizeof(txtName); }

Difficulty: Medium

Correct Answer: Above program will display size of integer.

Explanation:


Introduction / Context:
This classic trap distinguishes sizeof(pointer) from the length or contents of the string it points to. Here, only sizeof(txtName) is printed; the program never streams the string itself. On typical 16-bit DOS compilers (e.g., Turbo C/C++), both sizeof(int) and sizeof(char) are 2, so many exam sets phrase the answer as “size of integer.”


Given Data / Assumptions:

  • Legacy environment where sizeof(int)==sizeof(char)==2.
  • sizeof is compile-time and depends on the variable's type, not allocation.
  • No call to objTemp.Display(); only sizeof(txtName) is printed.


Concept / Approach:
txtName in main is a char*, so sizeof(txtName) equals the size of a pointer on the target model, not the string length and not the array size inside CuriousTabString.


Step-by-Step Solution:
1) txtName is declared as pointer: char*.2) sizeof(txtName) queries pointer size (commonly 2 bytes in 16-bit models).3) Therefore the output is the pointer size; traditional MCQs equate this to “size of integer” in those compilers since both are 2.


Verification / Alternative check:
Print sizeof(int) and sizeof(char*) side by side in Turbo C; values match.


Why Other Options Are Wrong:
They assume the string is printed or that length 8/9 appears, but the code never outputs the C-string. Printing 1 is unrelated.


Common Pitfalls:
Confusing the array inside the class (which would be 20) with the pointer variable in main.


Final Answer:
Above program will display size of integer.

More Questions from Functions

Discussion & Comments

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