The sizeof( ) operator

  • The size of a data type:

      • Size of a data type = the number of bytes of memory used to store a value of that data type.

  • Syntax on how to use the sizeof( ) operator:

         sizeof( dataType )    
    
               returns the size of a variable of type "dataType" 
    
      or
    
         sizeof( varName )     
    
               returns the size of the variable "varName" 

Example program showing the effect of the sizeof( ) operator

 

#include <stdio.h>

int main( int argc, char* argv[] )
{
   printf("sizeof(char)   = %lu\n", sizeof(char) );    // 1
   printf("sizeof(short)  = %lu\n", sizeof(short) );   // 2
   printf("sizeof(int)    = %lu\n", sizeof(int) );     // 4
   printf("sizeof(long)   = %lu\n", sizeof(long) );    // 8
   printf("\n");

   printf("sizeof(float)  = %lu\n", sizeof(float) );   // 4
   printf("sizeof(double) = %lu\n", sizeof(double) );  // 8
   printf("\n");

   int x;
   double y;

   printf("sizeof(x)      = %lu\n", sizeof(x) );       // 4
   printf("sizeof(x)      = %lu\n", sizeof(y) );       // 8
} 

Common usage of the sizeof( ) operator

  • Java has the new operator that allocate (= reserve) memory for objects of a certain class

  • The amount of memory that the new operator will allocate depends on the member variables in a class

      • The Java compiler will consult/read the class definition to determine the amount of memory needed.

  • In contrast, the C programming language does not have a new operator

  • The malloc( ) (memory allocate) C library function is used to allocate memory

  • The sizeof( ) operator is often used with the malloc( ) function to allocate (= reserve) memory to store structure (= "object") as follows:

      malloc( sizeof(userDataTypeName) ) // More detail later...