0
0
Embedded Cprogramming~5 mins

sizeof and memory budgeting in Embedded C

Choose your learning style9 modes available
Introduction

The sizeof operator helps you find out how much memory a variable or data type uses. This is important to plan and control memory use in small devices.

When you want to know how much memory a variable or data type takes.
When you need to allocate memory dynamically and want to avoid wasting space.
When you are working with limited memory in embedded systems and must budget carefully.
When you want to check the size of arrays or structures to avoid overflow.
When you want to write portable code that adapts to different hardware sizes.
Syntax
Embedded C
sizeof(expression_or_type)

The sizeof operator returns the size in bytes.

You can use it with a variable, a data type, or an expression.

Examples
Finds the size of the int type in bytes.
Embedded C
sizeof(int)
Finds the size of the variable myVariable. Parentheses are optional here.
Embedded C
sizeof myVariable
Finds the total size of the array in bytes (number of elements x size of each element).
Embedded C
sizeof(array)
Finds the size of a structure type MyStruct.
Embedded C
sizeof(struct MyStruct)
Sample Program

This program shows how to use sizeof to find the size of different types and variables. It also calculates how many elements are in an array by dividing the total size by the size of one element.

Embedded C
#include <stdio.h>

int main() {
    int a = 10;
    char b = 'x';
    double c = 3.14;
    int arr[5];

    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Size of variable a: %zu bytes\n", sizeof a);
    printf("Size of char: %zu bytes\n", sizeof(char));
    printf("Size of variable b: %zu bytes\n", sizeof b);
    printf("Size of double: %zu bytes\n", sizeof(double));
    printf("Size of variable c: %zu bytes\n", sizeof c);
    printf("Size of array arr: %zu bytes\n", sizeof arr);
    printf("Number of elements in arr: %zu\n", sizeof arr / sizeof arr[0]);

    return 0;
}
OutputSuccess
Important Notes

Sizes can vary depending on the hardware and compiler.

Use sizeof to avoid hardcoding sizes and make your code safer and portable.

Remember that sizeof returns size in bytes, which is the smallest addressable memory unit.

Summary

sizeof tells you how many bytes a type or variable uses.

It helps you plan memory use, especially in devices with limited memory.

Use it to find array sizes and avoid memory errors.