0
void printElements(int(arr)[4])   // option 1
//void printElements(int(&arr)[4])  // option 2
{
    int length( sizeof(arr) / sizeof(arr[0]) ); 
    std:: cout <<"length is "<< length << std::endl;
    for (int i( 0 ); i < length; ++i)
    {
        std::cout << arr[i] << std::endl;
    }
}

with the main function

int main() {
    int arr[]{99, 20, 14, 80};
    printElements(arr);
}

As listed, two options: one is void printElements(int(arr)[4]), another is void printElements(int(&arr)[4]). But the first one will cout the size of the array is 2. The second says the size of the array is 4. Why is the difference?

Marc-André
  • 325
  • 2
  • 17
John
  • 125
  • 1
  • 8
  • See https://stackoverflow.com/q/1461432/1782465 – Angew is no longer proud of SO Dec 06 '18 at 20:25
  • 3
    C-Arrays are really confusing, it you can, use `std::array` or `std::vector` instead – JVApen Dec 06 '18 at 20:25
  • Passing `int(arr)[4]` is just syntax sugar for passing the array as an `int*`, as an array *decays* into a pointer to its first element, thus `sizeof(arr) / sizeof(arr[0])` is the same as `sizeof(int*) / sizeof(int)`, which is 2 if `int*` is 4 bytes and `int` is 2 bytes (not many compilers use a 2-byte `int` nowadays, most have a 4-byte `int` instead). Passing `int (&arr)[4]` instead, there is no decay, thus `sizeof(arr) / sizeof(arr[0])` is the same as `sizeof(int[4]) / sizeof(int)`, which is always 4. – Remy Lebeau Dec 06 '18 at 20:32
  • 1
    This is sneaky behavior inherited from C. Arrays aren't passed by value to function arguments. `int(arr)[4]` is quietly replaced with `int * arr`. The size is not enforced. – François Andrieux Dec 06 '18 at 20:33
  • This question is closed for the **wrong** reason. Saying the array decays to a pointer is only half the answer. You also need to explain the reference part. – Martin York Dec 06 '18 at 20:40

0 Answers0