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.