C - Get a variable's size

Introduction

The following code uses the sizeof operator to determine how much storage each C language variable type occupies in memory.

Demo

#include <stdio.h> 

int main() //from w  w w .ja  va 2s.  com
{ 
   char c = 'c'; 
   int i = 123; 
   float f = 98.6; 
   double d = 6.022E23; 

   printf("char\t%u\n",sizeof(c)); 
   printf("int\t%u\n",sizeof(i)); 
   printf("float\t%u\n",sizeof(f)); 
   printf("double\t%u\n",sizeof(d)); 
   return(0); 
}

Result

The sizeof keyword isn't a function.

Its argument is a variable name. The value that's returned is of the C language variable type known as size_t.

Arrays are variables, and sizeof works on them.

Demo

#include <stdio.h> 

int main() /*from   w w  w.  j  a  va  2  s.  co  m*/
{ 
     char string[] = "Does this string make me look fat?"; 

     printf("The string \"%s\" has a size of %u.\n", 
             string,sizeof(string)); 
     return(0); 
}

Result

Related Topic