C The sizeof Operator

1. What is sizeof?

  • sizeof is a compile-time operator in C.

  • It returns the size (in bytes) of a data type, variable, array, or structure.

  • Syntax:

sizeof(variable_or_data_type)
  • The result is usually of type size_t (an unsigned integer type).


2. Using sizeof with Data Types

#include <stdio.h>

int main() {
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
printf("Size of char: %zu byte\n", sizeof(char));
return 0;
}

Output (typical on 32-bit/64-bit system):

Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte

%zu is used to print size_t type returned by sizeof.


3. Using sizeof with Variables

#include <stdio.h>

int main() {
int a;
float b;
double c;
char d;

printf("Size of a: %zu bytes\n", sizeof(a));
printf("Size of b: %zu bytes\n", sizeof(b));
printf("Size of c: %zu bytes\n", sizeof(c));
printf("Size of d: %zu byte\n", sizeof(d));

return 0;
}


4. Using sizeof with Arrays

  • For arrays, sizeof gives the total memory used.

  • You can calculate the number of elements using:

number_of_elements = sizeof(array) / sizeof(array[0]);

Example:

#include <stdio.h>

int main() {
int arr[10];
printf("Size of array: %zu bytes\n", sizeof(arr));
printf("Number of elements: %zu\n", sizeof(arr) / sizeof(arr[0]));
return 0;
}

Output:

Size of array: 40 bytes
Number of elements: 10

Here, each int is 4 bytes, so 10 × 4 = 40 bytes.


5. Using sizeof with Pointers

#include <stdio.h>

int main() {
int *ptr;
printf("Size of pointer: %zu bytes\n", sizeof(ptr));
return 0;
}

  • Pointer size is independent of data type it points to.

  • Typically 4 bytes on 32-bit and 8 bytes on 64-bit systems.


6. Key Points

  1. sizeof is evaluated at compile time.

  2. Can be used with data types, variables, arrays, and structures.

  3. Useful for memory calculations, dynamic allocation, and array sizing.

  4. Returns size in bytes.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *