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 (0)