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/
Top comments (1)
When an array is used anywhere (except as an argument to
sizeof), it decays into a pointer to a first element.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.C even allows a bizarre syntax for declaring a constant "array":
Hence, when you use
sizeoffor 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 forsizeof.