1

I saw this code and unable to understand the output of code. In main function sizeof(a) prints 40. But when i pass the array to function, sizeof(arr) print 8. Anyone can explain the behaviour??

#include <iostream>
using namespace std;

void findSize(int arr[]){
    cout<<sizeof(arr)<<endl;
}
int main() {
    int a[10];
    cout<<sizeof(a)<<" ";
    findSize(a);
    return 0;
}
  • Your array decays to a pointer. – erip Mar 18 '22 at 11:24
  • https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay – abelenky Mar 18 '22 at 11:24
  • `arr` is of type `int*`, and the size of any pointer type is 8 (on a 64 bit CPU) – PMF Mar 18 '22 at 11:25
  • you cannot pass arrays to functions by value. What is actually passed to the function is a pointer – 463035818_is_not_an_ai Mar 18 '22 at 11:34
  • 3
    @PMF: The size of a pointer is determined by the C implementation, not by the CPU. I have used a C implementation with 32-bit pointers on a “64-bit CPU.” – Eric Postpischil Mar 18 '22 at 11:41
  • 1
    The size of a pointer often corresponds to the size of the _address bus_, which is not necessarily of the same width as the CPU data size. For example pretty much every single 8 bit MCU out there has a 16 bit address bus and 16 bit C pointers. – Lundin Mar 18 '22 at 11:50
  • 1
    About terminology: `sizeof` is not a function; it's an operator. Yes, it usually looks like a function call, but that doesn't make it one. And, just to confuse things further, you can write `sizeof 3` (but you can't write `sizeof int`). Formally, it has two forms: `sizeof expression` and `sizeof ( type )`. Of course, an expression can be surrounded by parentheses, so `sizeof (3)` is okay. – Pete Becker Mar 18 '22 at 12:56
  • `sizeof` is not a function, and it does not "_print_" anything - `cout` did that. – Clifford Mar 18 '22 at 20:55

0 Answers0