DEV Community

Ujjawal Chaudhary
Ujjawal Chaudhary

Posted on

Day 4: The Sizeof Trap: Understanding Array Decay in C

If you pass an array to a function in C, you might be in for a rude awakening when you check its size.

This is called Array Decay.

When an array is passed to a function, it "decays" into a simple pointer to its first element. It forgets how long it is.

  • Inside main, sizeof(arr) tells you the total bytes of the array.
  • Inside a function, sizeof(arr) only tells you the size of the pointer address (usually 8 bytes on 64-bit systems).

The Code

Run this code to see the "Lie" in action.



// Day 4: Arrays vs. Pointers (The Nuance)

#include <stdio.h>

void print_size(int arr[]) {
    // WARNING: 'arr' here has decayed to a pointer!
    // It is no longer an array.
    printf("Size inside function: %zu bytes (Pointer size)\n", sizeof(arr));
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};

    // 1. Size of the Array in local scope
    // Returns 20 (5 ints * 4 bytes each)
    printf("Size in main: %zu bytes\n", sizeof(arr));

    // 2. Pass it to a function
    print_size(arr);

    return 0;
}

πŸ“‚ View the source code on GitHub:https://github.com/Ujjawal0711/30-Days/
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

When an array is passed to a function, it "decays" into a simple pointer to its first element.

When an array is used anywhere (except as an argument to sizeof), it decays into a pointer to a first element.

int a[4];
int *p = a;  // "a" decayed β€” no function needed
Enter fullscreen mode Exit fullscreen mode

When you pass an array to a function, the decay also happens (as it does above with the assignment to p). The problem is that, despite appearances, array parameters simply don't exist in C. C allows a "fossil" syntax for declaring pointer function arguments.

void f( int a[] ) {  // as if: int *a
  ++a;               // even this is legal
  // ...
Enter fullscreen mode Exit fullscreen mode

C even allows a bizarre syntax for declaring a constant "array":

void g( int a[const] ) {  // as if: int *const a
Enter fullscreen mode Exit fullscreen mode

Hence, when you use sizeof for a function parameter, you're using it on a pointer despite the syntax. It's the special-case fossil syntax that's the crux of the problem, not another special-case for sizeof.