UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

6.4.  The sizeof() function

To reserve memory, the exact number of bytes that any data structure occupies must be known. As it was mentioned previously, a special feature of the C programming language is that the size of its data structures may vary between platforms. How do we know how many bytes to reserve to store, for example 10 integers? The language itself offers the solution to this problem through the function sizeof().

The function receives as the only parameter the name of one variable or the name of a data type and returns its size in bytes. With this definition, then, sizeof(int) returns the number of bytes that are used to store an integer. The function can also be invoked with structured data types or unions as shown in the following program (which we recommend you download, compile and execute it):

#include <stdio.h>
#define NAME_LENGTH 10
#define TABLE_SIZE 100
#define UNITS_NUMBER 10

struct unit
{  /* Define a struct with an internal union */
  int x;
  float y;
  double z;
  short int a;
  long b;
  union
  { /* Union with no name because it is internal to the struct */
    char name[NAME_LENGTH];
    int id;
    short int sid;
  } identifier;
};

int main(int argc, char *argv[])
{
  int table[TABLE_SIZE];
  struct unit data[UNITS_NUMBER];

  printf("%d\n", sizeof(struct unit)); /* Print size of structure */
  printf("%d\n", sizeof(table));       /* Print size of table of ints */
  printf("%d\n", sizeof(data));        /* Print size of table of structs */

  return 0;
}

With this function you may solve any doubt you might have about the size of any data structure. You simply write a program that prints its size with sizeof().