C sizeof() operator

The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.

Need of sizeof() operator

Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator:

snippet
int *ptr=malloc(10*sizeof(int));

In the above example, we use the sizeof() operator, which is applied to the cast of type int. We use malloc() function to allocate the memory and returns the pointer which is pointing to this allocated memory. The memory space is equal to the number of bytes occupied by the int data type and multiplied by 10.

Note
Note:
The output can vary on different machines such as on 32-bit operating system will show different output, and the 64-bit operating system will show the different outputs of the same data types.

The sizeof() operator behaves differently according to the type of the operand.

  • Operand is a data type
  • Operand is an expression

When operand is a data type.

snippet
#include <stdio.h>
int main()
{
    int x=89;    // variable declaration.
    printf("size of the variable x is %d", sizeof(x));  // Displaying the size of ?x? variable.
    printf("\nsize of the integer data type is %d",sizeof(int)); //Displaying the size of integer data type.
    printf("\nsize of the character data type is %d",sizeof(char)); //Displaying the size of character data type.

    printf("\nsize of the floating data type is %d",sizeof(float)); //Displaying the size of floating data type.
return 0;
}

In the above code, we are printing the size of different data types such as int, char, float with the help of sizeof() operator.

Output

sizeof() operator in C

When operand is an expression

snippet
#include <stdio.h>
int main()
{
  double i=78.0; //variable initialization.
  float j=6.78; //variable initialization.
  printf("size of (i+j) expression is : %d",sizeof(i+j)); //Displaying the size of the expression (i+j).
  return 0;
}

In the above code, we have created two variables 'i' and 'j' of type double and float respectively, and then we print the size of the expression by using sizeof(i+j) operator.

Output

Output
size of (i+j) expression is : 8
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +