SIZEOF

this operator is used to compute the size of its operand. it returns the size of a variable or the keyword that defines a type (int, char, etc) including types defined by the typedef keyword, expressions, and pointer type variables. this operator returns a number of type size_t.

int i; char c;
i = sizeof c;

 * may not use parentheses with the sizeof operator when the argument is a 
   literal or a value

char tab[10];
i = sizeof tab;

 *  i is set to the value of 10, because this is the number of bytes occupied by the 
    entire tab array

char tab[10];
i = sizeof tab[1];
 
 * i is set to the value of 1, because it points to the first element
#include <stdio.h>

int main(int argc, char *argv[])
{
  int integerValue = 16;
  double doubleValue = 4.65;
  
  printf("Size of int data type: %zu\n", sizeof(int));
  printf("Size of double data type: %zu\n", sizeof(double));
  
  printf("\nSize of integerValue variable: %zu\n", sizeof(integerValue));
  printf("Size of doubleValue variable: %zu\n", sizeof(doubleValue));
  
  return 0;
}

AUTO-CALCULATING ARRAY SIZE:

root@dev:~$ vim fileName.c
 ...
 int int_array[] = {100, 200, 300, 400};
 int num_ints    = sizeof(int_array) / sizeof(int);
 ...
 
 * the sizeof(int_array) returns the total size, in bytes, of the entire int_array. 
   For example, if int_array has 4 integers and each integer takes up 4 bytes, 
   sizeof(int_array) would return 16
   
 * the sizeof(int) returns the size, in bytes, of a single integer variable on the 
   system where the code is being compiled. This can vary depending on the architecture
   (e.g., 4 bytes on many modern systems, but potentially 2 or 8 bytes on others).

 * this is a good practice in C and C++ because it avoids "hardcoding" the size of 
   the array into your code. If you later change the size of int_array, you don't 
   need to remember to update the number of elements in multiple places. The sizeof 
   operator will automatically calculate the correct number

AUTO-CALCULATING ARRAY SIZE: W/O THE NULL TERMINATOR

root@dev:~$ vim fileName.c
 ...
 char string[] = "Hey you!";
 int num_chars = sizeof(string) / sizeof(char) - 1;
 ...
 
 * the sizeof(string) returns the total size, in bytes, of the string array. Since 
   each char takes up 1 byte, sizeof(string) will be 9 (because there are 9 characters)
    - this include the null terminator
 * the sizeof(char) returns the size, in bytes, of a single char variable. This is 
   almost always 1 byte.
 * - 1 is the key part. 1 is subtracted from the total number of characters 
   because the null terminator shouldn't be included in the count of meaningful 
   characters. The null terminator is used to mark the end of the string, but it's 
   not part of the visible text

Last updated