C sizeof operator

Created By: chatGPT

C provides a powerful sizeof operator that allows you to determine the size, in bytes, of a data type or an object in memory. This can be particularly useful when dynamically allocating memory or performing low-level data manipulation.
// Example of using sizeof operator
#include <stdio.h>

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

    printf("Size of int: %zu bytes\n", sizeof(a));
    printf("Size of double: %zu bytes\n", sizeof(b));
    printf("Size of char: %zu bytes\n", sizeof(c));

    return 0;
}
You can also use sizeof with custom data types, like structures and arrays. It helps you understand how much memory a data structure will occupy.
// Example of sizeof with structures
#include <stdio.h>

typedef struct {
    int id;
    char name[50];
} Student;

int main() {
    printf("Size of Student structure: %zu bytes\n", sizeof(Student));
    return 0;
}
When using sizeof on arrays, it returns the total size of the array, which is the size of the individual element multiplied by the number of elements.
// Example of sizeof with arrays
#include <stdio.h>

int main() {
    int numbers[10];
    size_t size = sizeof(numbers);
    size_t element_size = sizeof(numbers[0]);
    size_t num_elements = size / element_size;

    printf("Total size of array: %zu bytes\n", size);
    printf("Number of elements in the array: %zu\n", num_elements);

    return 0;
}
It is important to note that sizeof is evaluated at compile-time for static types. Therefore, it is particularly useful in situations where performance is critical, as it avoids the overhead of function calls.
// Performance aspect of sizeof
#include <stdio.h>

int main() {
    printf("Size of int using sizeof: %zu bytes\n", sizeof(int));
    printf("Size of pointer using sizeof: %zu bytes\n", sizeof(int*));
    return 0;
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharVoidUnsignedSignedConstantsEnumerationsArraysStringsStructsUnionsTypedefsPointersDynamic Memory AllocationMallocCallocReallocFreeFunctionsFunction DeclarationsFunction DefinitionsFunction CallsReturn StatementInline FunctionsRecursionHeader FilesPreprocessor DirectivesControl FlowIf StatementElse StatementElse If StatementSwitch StatementCase StatementDefault CaseLoopsFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementLabelsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional (ternary) OperatorComma OperatorSizeof OperatorData StructuresLinked ListsStacksQueuesTreesGraphsFunction PointersCallbacksMacrosCommentsSingle Line CommentsMulti Line CommentsSyntaxSyntax ErrorsCompilation ErrorsDebuggingStandard Input OutputPrintfScanfFile HandlingFopenFcloseFreadFwriteFprintfFgetsFputsError HandlingErrnoAssertionsExit FunctionExit CodesEvent HandlingSignal HandlingInterrupts