C++ pointer size vs. string contents: what does this program actually print when taking sizeof on a char* variable (legacy headers)? #include<iostream.h> #include<string.h> #include<malloc.h> class CuriousTabString{ char txtName[20]; public: CuriousTabString(char txtTemp=NULL){ if(txtTemp!=NULL) strcpy(txtName, txtTemp); } void Display(){ cout << txtName; } }; int main(){ char txtName=(char)malloc(10); strcpy(txtName, "CuriousTab"); txtName = 48; // overwrite first char CuriousTabString objTemp(txtName); cout << sizeof(txtName); }
-
AAbove program will display CuriousTab 8.
-
BAbove program will display CuriousTab 9.
-
CAbove program will display size of integer.
-
DAbove program will display CuriousTab and size of integer.
-
EAbove program will display 1.
Answer
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. sizeofis compile-time and depends on the variable's type, not allocation.- No call to
objTemp.Display(); onlysizeof(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.