What is array-to-pointer decay in C++?
Hello colleagues! I've just started learning C++ and encountered very strange behavior with arrays. When I pass an array to a function and try to find its size using `sizeof`, I get something unexpected.
Here's an example:
```cpp
#include
void printSize(int arr[]) {
std::cout << "Inside function: " << sizeof(arr) << " bytes" << std::endl;
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
std::cout << "In main: " << sizeof(numbers) << " bytes" << std::endl; // Outputs 20 (5 * 4)
printSize(numbers); // Outputs 8 (pointer size) on 64-bit system
return 0;
}
```
I expected that inside the function `sizeof(arr)` would also return 20, but I get 8. Why does this happen? I've heard the term "array decay" but don't fully understand what it means.
No answers yet.
Log in to leave an answer