I noticed sometime back that one of my programs behaved unexpectedly in certain scenarios which was traced to an incorrect use of sizeof. As a result, I made a small program to make sure that my understanding of sizeof is correct. Here is the program:
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
using namespace std;
int main()
{
char a[]="";
cout<<"Size of a[] = "<<sizeof(a)<<endl;
char b[]=" ";
cout<<"Size of b[ ] = "<<sizeof(b)<<endl;
char c[10];
cout<<"Size of c[10] = "<<sizeof(c)<<endl;
char* d;
cout<<"Size of d = "<<sizeof(d)<<endl;
char* e = c;
cout<<"Size of e = "<<sizeof(e)<<endl;
char f[] = "123456";
cout<<"Size of f = "<<sizeof(f)<<endl;
char g[] = {'1','2','3','4','5','6'};
cout<<"Size of g = "<<sizeof(g)<<endl;
return 0;
}
The output is as follows:
A lot of interviewers love the sizeof questions.Have you come across any interesting sizeof problems? Please feel free to add them in comments.
the following is the output by turbo c++ 3.0:
ReplyDeleteby char pointer is 0f 4 bytes in your output:
╔═[■]═══════════════════════════════ Output ═════════════════════════════3═[↕]═╗
║Size of a[] = 1 ▲
║Size of b[ ] = 2 ■
║Size of c[10] = 10 ▒
║Size of d = 2 ▒
║Size of e = 2 ▒
║Size of f = 7 ▒
║Size of g = 6 ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▼
╚═◄■▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒►─┘
F1 Help ↑↓←→ Scroll
hey when the above program is executed by turbo c++ 3.0 then sizeof takes the size of ch pointer as 2...y..???
ReplyDelete╔═[■]═══════════════════════════════ Output ═════════════════════════════3═[↕]═╗
║Size of a[] = 1 ▲
║Size of b[ ] = 2 ■
║Size of c[10] = 10 ▒
║Size of d = 2 ▒
║Size of e = 2 ▒
║Size of f = 7 ▒
║Size of g = 6 ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▒
║ ▼
╚═◄■▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒►─┘
F1 Help ↑↓←→ Scroll
The size of d and e is the size of pointer. Is your Turbo C++ compiler 16 bit? In that case the size of pointer will be 2 bytes rather than 4 bytes.
ReplyDelete