Arrays December 19 ,2025

Table of Contents

  • 1.32. 13. Passing Arrays to Functions (Deep)
  • 1.33. 14. Passing 2D Arrays to Functions
  • 1.34. 15. Dynamic Arrays: Step-by-Step Internals
  • 1.35. 16. realloc(): How Dynamic Arrays Grow
  • 1.36. 17. Static vs Dynamic Arrays (Deep Comparison)
  • 1.37. 18. Undefined Behavior in Arrays (Very Important)
  • 1.38. 19. Real-World Bugs Caused by Arrays
  • 1.39. 20. Why Arrays in C Are the Foundation of DSA
  • Arrays in C – 

    (From Memory Model to Real-World Bugs)

    1. Arrays in C: Conceptual Definition (Compiler Level)

    In C, an array is a contiguous block of memory locations that stores elements of the same data type, accessed using zero-based indexing.

    But internally, the compiler treats an array as:

    • A symbolic name bound to a fixed memory location
    • NOT a variable
    • NOT a pointer variable
    • A block whose size is known at compile time (for static arrays)

    This is critical:

    An array name is not modifiable.

    2. Array Declaration: What Compiler Actually Does

    Code

    int arr[5];
    

    Compiler actions:

    1. Reserves 5 × sizeof(int) bytes
    2. Chooses stack or data segment (based on scope)
    3. Associates symbol arr with the base address
    4. No default initialization for local arrays

    If declared globally:

    int arr[5];
    

    → Automatically initialized to 0.

    3. Where Arrays Live in Memory

    Array TypeMemory Segment
    Global arrayData segment
    Static arrayData segment
    Local arrayStack
    Dynamic arrayHeap

    Example

    int globalArr[10];        // Data segment
    static int staticArr[5]; // Data segment
    
    int main() {
        int localArr[5];     // Stack
    }
    

    4. Array Name vs Pointer: Deep Truth

    PropertyArray NamePointer
    Stores addressYesYes
    ModifiableNoYes
    Size infoYes (compile time)No
    ArithmeticLimitedFull
    ReassignableNoYes

    Proof Code

    int arr[5];
    int *p = arr;
    
    p = p + 1;    // valid
    arr = arr+1; // invalid
    

    Why?

    • arr is a constant pointer
    • p is a variable pointer

    5. Array Decay Rule 

    In most expressions, the name of an array automatically converts (decays) into a pointer to its first element.

    In simple words

    • arr → behaves like &arr[0]
    • Type becomes pointer to element type

    Basic Example

    int arr[5];
    int *p = arr;
    

    What Happens Internally

    • arr decays to &arr[0]
    • p stores the address of the first element

    Equivalent to:

    int *p = &arr[0];
    

    Memory Relation

    arr      → address of first element
    &arr[0]  → address of first element
    

    But types are different:

    • arr → int[5]
    • &arr → int (*)[5]

    When Array Decay DOES NOT Happen

    Array decay does not occur in the following cases:

    A. When used with sizeof method

    Example

    sizeof(arr);
    

    Explanation

    • Returns total size of the array
    • Array name is treated as a complete array, not a pointer

    If:

    • int = 4 bytes
    • arr[5]

    Then:

    sizeof(arr) = 5 × 4 = 20 bytes
    

    . When Used with Address-of Operator (&)

    Example

    sizeof(&arr);
    

    Explanation

    • &arr gives the address of the entire array
    • Type becomes pointer to array, not pointer to element
    ExpressionType
    arrint[5]
    &arrint (*)[5]

    3. When Array Is a Function Parameter

    Example

    void func(int arr[]) {
        printf("%lu", sizeof(arr));
    }
    

    Explanation

    • Array parameter automatically decays to pointer
    • Compiler treats it as:
    void func(int *arr)
    

    So:

    sizeof(arr)  // returns size of pointer, NOT array
    

    Comparison Example

    int arr[5];
    
    printf("%lu\n", sizeof(arr));    // 20 bytes
    printf("%lu\n", sizeof(&arr));   // size of pointer to array
    

    Key Differences Table

    ExpressionMeaningDecay?
    arrPointer to first elementYes
    &arrPointer to whole arrayNo
    sizeof(arr)Total array sizeNo
    sizeof(&arr)Pointer sizeNo
    Array as parameterPointerAlready decayed

    Important Exam Points

     Array name decays to pointer to first element
     Decay does not happen with sizeof and &
     Arrays passed to functions lose size information
     arr and &arr point to same address but have different types

    Common Interview Trick Question

    int arr[10];
    printf("%lu %lu", sizeof(arr), sizeof(arr + 1));
    

    Output

    40 8   // (on 64-bit system)
    

    Why?

    • arr → array (40 bytes)
    • arr + 1 → pointer arithmetic → size of pointer

    6. size of Array vs size of Pointer (Critical)

    What is a Pointer?

    A pointer is a variable that stores the address of another variable.

    int x = 10;
    int *p = &x;   // p stores the address of x 
    • p does not store the value 10
    • It stores where 10 is located in memory

    Code

    #include 
    
    int main() {
        int arr[10];
        int *p = arr;
    
        printf("%lu\n", sizeof(arr)); // 40
        printf("%lu\n", sizeof(p));   // 8
    }
    

    Why?

    • arr → full block
    • p → only address

    Difference Between Array and Pointer

    FeatureArrayPointer
    DefinitionCollection of elements of same type stored contiguouslyVariable that stores address of another variable
    MemoryAllocates actual memory for elementsStores only an address
    Size (sizeof)Total size = number of elements × size of datatypeFixed size (4 bytes in 32-bit, 8 bytes in 64-bit)
    AddressArray name represents base addressPointer holds an address
    Reassignment❌ Cannot be reassigned✅ Can be reassigned
    IndexingDirect indexing (arr[i])Indirect (*(p + i))
    ArithmeticLimitedFull pointer arithmetic allowed
    When passed to functionConverted to pointerPassed as pointer
    Memory ownershipOwns its memoryDoes not own memory
    Initializationint arr[3] = {1,2,3};int *p = arr;

    Example

    int arr[3] = {10, 20, 30};
    int *p = arr;
    

    Accessing elements

    arr[1];      // 20
    p[1];        // 20
    *(p + 1);    // 20
    

     Same output, different meaning internally

     

    7. Array Indexing: Compiler Translation

    Code

    arr[i]
    

    Internally converted to:

    *(arr + i)
    

    Even:

    i[arr]
    

    is valid in C (because addition is commutative).

    8. Pointer Arithmetic: Byte-Level Explanation

    Assume:

    int arr[3];
    

    If base address = 1000

    ExpressionAddress
    arr1000
    arr+11004
    arr+21008

    Because:

    arr + i = base + i × sizeof(int)
    

    9. Traversing Arrays: Assembly Perspective

    Index Traversal

    arr[i]
    

    Pointer Traversal

    *(p+i)
    

    Modern compilers generate same assembly code for both.

    So:

    • Choice is readability
    • Not performance

    10. Multidimensional Arrays: Memory Reality

    Declaration

    int a[2][3];
    

    Memory:

    a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
    

    C uses row-major order.

    11. Address Formula for 2D Arrays

    For:

    int a[R][C];
    

    Address of a[i][j]:

    Base + ((i × C) + j) × sizeof(int)
    

    Compiler MUST know column size.

    12. Why int** Is NOT a 2D Array

    Wrong Thinking

    int **p;
    

    Many people think this represents a 2D array.

     This is incorrect.

    Reality

    What int** Means

    int**  → pointer to a pointer to int
    

    It means:

    • p points to a pointer
    • That pointer points to an int

    Memory Representation

    p
     ↓
    ptr1 ──► int
    

    This structure does not guarantee contiguous memory.

    What a 2D Array Actually Is?

    Definition

    A 2D array is an array of arrays stored in contiguous memory.

    Example

    int a[2][3];
    

    This means:

    • a is an array of 2 elements
    • Each element is an array of 3 ints

    Memory layout:

    [1][2][3][4][5][6]   // contiguous
    

    Key Difference

    Aspectint**int[2][3]
    NaturePointer to pointerArray of arrays
    MemoryNot contiguousContiguous
    Row size known?❌ No✅ Yes
    Pointer arithmeticDifferentPredictable
    Compiler knows layout❌ No✅ Yes

    Why int** Fails as a 2D Array

    Example

    int a[2][3];
    int **p = a;   // ❌ WRONG
    

    Why Wrong?

    • a decays to int (*)[3]
    • But int** expects int*
    • Types are incompatible

    Correct Pointer for a 2D Array

    Correct Declaration

    int (*p)[3] = a;
    

    What This Means

    p → pointer to an array of 3 integers
    

    Now:

    p[i][j]  // works correctly
    

    Understanding int in This Context

    What Is int?

    int is:

    • A basic data type
    • Typically occupies 4 bytes
    • Used to store whole numbers

    In:

    int (*p)[3];
    
    • int → type of each element
    • [3] → number of columns
    • (*p) → pointer
    • Full meaning:
    p is a pointer to an array of 3 integers
    

    Visual Comparison

    int** (Pointer to Pointer)

    p ──► p1 ──► int
    

    2D Array Pointer (int (*p)[3])

    p ──► [int int int] [int int int]
    

    Important Exam Points

    ✔ int** ≠ 2D array
    ✔ 2D array = array of arrays
    ✔ Use int (*p)[columns]
    ✔ Compiler must know column size
    ✔ int** is suitable for jagged arrays, not true matrices

    When int** Is Actually Useful

    • Dynamic jagged arrays
    • When each row has different size
    • Dynamic memory allocation using malloc
       

    13. Passing Arrays to Functions (Deep)

    When passed:

    func(arr);
    

    Compiler converts to:

    func(&arr[0]);
    

    Only address is passed → no copy.

    Code

    void modify(int arr[]) {
        arr[0] = 99;
    }
    

    Change reflects in main.

    14. Passing 2D Arrays to Functions

    Correct Way

    void func(int arr[][3], int rows);
    

    Or

    void func(int (*arr)[3], int rows);
    

    Column size mandatory.

    15. Dynamic Arrays: Step-by-Step Internals

    Code

    int *arr = malloc(5 * sizeof(int));
    

    What happens:

    1. Heap memory allocated
    2. Base address returned
    3. Pointer stores address
    4. Programmer responsible for free

    Memory Leak Example

    arr = malloc(10 * sizeof(int));
    // lost old pointer → leak
    

    16. realloc(): How Dynamic Arrays Grow

    arr = realloc(arr, 10 * sizeof(int));
    

    Possible outcomes:

    • Memory extended in place
    • New block allocated and copied
    • Old block freed automatically

    17. Static vs Dynamic Arrays (Deep Comparison)

    FeatureStaticDynamic
    Allocation timeCompileRuntime
    ResizeImpossiblePossible
    SpeedFasterSlightly slower
    SafetySaferRisky
    Memory controlLowHigh

    18. Undefined Behavior in Arrays (Very Important)

    Examples:

    arr[10] = 5;     // out of bounds
    free(arr); free(arr); // double free
    use after free
    

    C does NOT protect you.

    19. Real-World Bugs Caused by Arrays

    • Buffer overflow
    • Stack smashing
    • Memory corruption
    • Security vulnerabilities

    Most security exploits originate from bad array handling.

    20. Why Arrays in C Are the Foundation of DSA

    Arrays in C teach:

    • Memory layout
    • Pointer arithmetic
    • Performance thinking
    • Hardware awareness

    If you master arrays in C:

    • All other data structures become easier
    • Debugging skill increases dramatically

    Next Blog-
    Vector in C++ STL (safe dynamic arrays)

     

     

    Sanjiv
    0

    You must logged in to post comments.

    Related Blogs

    Find the S...
    Arrays February 02 ,2026

    Find the Second Smal...

    Array Memo...
    Arrays December 12 ,2025

    Array Memory Represe...

    Array Oper...
    Arrays December 12 ,2025

    Array Operations and...

    Advantages...
    Arrays December 12 ,2025

    Advantages and Disad...

    Vector in...
    Arrays December 12 ,2025

    Vector in C++ STL

    Arrays vs...
    Arrays December 12 ,2025

    Arrays vs ArrayList...

    JavaScript...
    Arrays December 12 ,2025

    JavaScript Arrays

    Binary Sea...
    Arrays December 12 ,2025

    Binary Search on Arr...

    Two Pointe...
    Arrays January 01 ,2026

    Two Pointers Techniq...

    Prefix Sum...
    Arrays January 01 ,2026

    Prefix Sum Technique

    Find the S...
    Arrays January 01 ,2026

    Find the Sum of All...

    Find the M...
    Arrays January 01 ,2026

    Find the Maximum Ele...

    Find the M...
    Arrays January 01 ,2026

    Find the Minimum Ele...

    Count Even...
    Arrays January 01 ,2026

    Count Even and Odd N...

    Search an...
    Arrays January 01 ,2026

    Search an Element in...

    Copy One A...
    Arrays January 01 ,2026

    Copy One Array into...

    Reverse an...
    Arrays January 01 ,2026

    Reverse an Array

    Print Alte...
    Arrays January 01 ,2026

    Print Alternate Elem...

    Find the L...
    Arrays January 01 ,2026

    Find the Length of a...

    Check if a...
    Arrays January 01 ,2026

    Check if an Array is...

    Find the F...
    Arrays January 01 ,2026

    Find the First Eleme...

    Find the L...
    Arrays January 01 ,2026

    Find the Last Elemen...

    Count the...
    Arrays January 01 ,2026

    Count the Number of...

    Replace Al...
    Arrays January 01 ,2026

    Replace All Elements...

    Sum of Ele...
    Arrays January 01 ,2026

    Sum of Elements at E...

    Sum of Ele...
    Arrays January 01 ,2026

    Sum of Elements at O...

    Find the A...
    Arrays January 01 ,2026

    Find the Average of...

    Count the...
    Arrays January 01 ,2026

    Count the Number of...

    Remove Dup...
    Arrays January 01 ,2026

    Remove Duplicate Ele...

    Move All Z...
    Arrays January 01 ,2026

    Move All Zeros to th...

    Rotate an...
    Arrays January 01 ,2026

    Rotate an Array by K...

    Rotate an...
    Arrays January 01 ,2026

    Rotate an Array by O...

    Check if T...
    Arrays January 01 ,2026

    Check if Two Arrays...

    Merge Two...
    Arrays January 01 ,2026

    Merge Two Sorted Arr...

    Find Missi...
    Arrays January 01 ,2026

    Find Missing Number...

    Find Dupli...
    Arrays January 01 ,2026

    Find Duplicate Eleme...

    Count Freq...
    Arrays January 01 ,2026

    Count Frequency of E...

    Find the M...
    Arrays January 01 ,2026

    Find the Majority El...

    Find All U...
    Arrays January 01 ,2026

    Find All Unique Elem...

    Insert an...
    Arrays January 01 ,2026

    Insert an Element at...

    Delete an...
    Arrays January 01 ,2026

    Delete an Element fr...

    Find the I...
    Arrays January 01 ,2026

    Find the Index of an...

    Find Union...
    Arrays January 01 ,2026

    Find Union of Two Ar...

    Find Inter...
    Arrays January 01 ,2026

    Find Intersection of...

    Sort an Ar...
    Arrays January 01 ,2026

    Sort an Array of 0s...

    Find the L...
    Arrays January 01 ,2026

    Find the Largest Sum...

    Kadane’s A...
    Arrays January 01 ,2026

    Kadane’s Algorithm (...

    Two Sum Pr...
    Arrays January 01 ,2026

    Two Sum Problem

    Subarray w...
    Arrays January 01 ,2026

    Subarray with Given...

    Longest Su...
    Arrays January 01 ,2026

    Longest Subarray wit...

    Rearrange...
    Arrays January 01 ,2026

    Rearrange Array Alte...

    Leaders in...
    Arrays January 01 ,2026

    Leaders in an Array

    Equilibriu...
    Arrays January 01 ,2026

    Equilibrium Index of...

    Stock Buy...
    Arrays January 01 ,2026

    Stock Buy and Sell (...

    Stock Buy...
    Arrays January 01 ,2026

    Stock Buy and Sell (...

    Sort an Ar...
    Arrays January 01 ,2026

    Sort an Array of 0s,...

    Find the M...
    Arrays January 01 ,2026

    Find the Majority El...

    Find All P...
    Arrays January 01 ,2026

    Find All Pairs with...

    Longest Co...
    Arrays January 01 ,2026

    Longest Consecutive...

    Product of...
    Arrays January 01 ,2026

    Product of Array Exc...

    Maximum Pr...
    Arrays January 01 ,2026

    Maximum Product Suba...

    Find the F...
    Arrays January 01 ,2026

    Find the First Missi...

    Count Inve...
    Arrays January 01 ,2026

    Count Inversions in...

    Rearrange...
    Arrays January 01 ,2026

    Rearrange Array by S...

    Check if A...
    Arrays January 01 ,2026

    Check if Array Can B...

    Trapping R...
    Arrays January 01 ,2026

    Trapping Rain Water

    Find Minim...
    Arrays January 01 ,2026

    Find Minimum in Rota...

    Search in...
    Arrays January 01 ,2026

    Search in Rotated So...

    Median of...
    Arrays January 01 ,2026

    Median of Two Sorted...

    Merge Inte...
    Arrays January 01 ,2026

    Merge Intervals

    Count Reve...
    Arrays January 01 ,2026

    Count Reverse Pairs

    Longest Su...
    Arrays January 01 ,2026

    Longest Subarray wit...

    Largest Re...
    Arrays January 01 ,2026

    Largest Rectangle in...

    Maximum Su...
    Arrays January 01 ,2026

    Maximum Sum Rectangl...

    Subarray S...
    Arrays January 01 ,2026

    Subarray Sum Equals...

    Count Dist...
    Arrays January 01 ,2026

    Count Distinct Eleme...

    Sliding Wi...
    Arrays January 01 ,2026

    Sliding Window Maxim...

    Find K Max...
    Arrays January 01 ,2026

    Find K Maximum Eleme...

    Minimum Nu...
    Arrays January 01 ,2026

    Minimum Number of Ju...

    Chocolate...
    Arrays January 01 ,2026

    Chocolate Distributi...

    Find All T...
    Arrays January 01 ,2026

    Find All Triplets Wi...

    Kth Smalle...
    Arrays January 01 ,2026

    Kth Smallest Element...

    Maximum Le...
    Arrays January 01 ,2026

    Maximum Length Biton...

    Find the S...
    Arrays February 02 ,2026

    Find the Second Larg...

    Get In Touch

    Kurki bazar Uttar Pradesh

    +91-8808946970

    techiefreak87@gmail.com