Department of Engineering

IT Services

C++ and sizeof

sizeof is an operator (like +) not a function (like sin). It needs a single operand. The operand can be a variable (in which case the operand needs to be bracketed) or a variable type. In either situation it tells you the number of bytes that an item of that type requires.

When sizeof is used on an array, it doesn't consider the current contents of the array, only the maximum capacity.

When sizeof is used on a class, the result is the number of bytes in an object of that type, which might be more than the sum of the parts - the object might have "padding" because (for example) some variables might only be allowed to start at even memory location.

The following program illustrates some of these points.

#include <iostream>
using namespace std;

int main() {
  cout << "Size of char=" << sizeof (char) << endl;
  int i;
  cout  << "Size of i="<< sizeof i << endl;

  class twin {
    char c; 
    int i;
  };
  cout  << "Size of twin="<< sizeof (twin) << endl;

  char str1[]="hello";
  char *strpointer= str1;
  char str2[10]="hello";
  string str3="hello";

  cout  << "Size of str1=" <<  sizeof str1 << endl;
  cout  << "Size of strpointer=" <<  sizeof strpointer << endl;
  cout  << "Size of str2=" <<  sizeof str2 << endl;
  cout  << "Size of str3=" <<  sizeof str3 << endl;
}

What this produces depends on the machine/compiler you use. For me it produces

Size of char=1
Size of i=4
Size of twin=8
Size of str1=6
Size of strpointer=8
Size of str2=10
Size of str3=8

If you want to find the current length of a character array, use strlen. If you want to find the length of a string use the length member function (in this case str3.length()).