0

Why does it print different results when printing sizeof of an array in function vs in main? And how do I fix this?

#include<iostream>

int array[5];

void Help(int array[5]){
    std::cout << sizeof(array) / sizeof(int) << std::endl;
    // PRINTS 1
}

int main(){
    Help(array);

    std::cout << sizeof(array) / sizeof(int) << std::endl;
    // PRINTS 5

    return 0;
}
Jastcher
  • 3
  • 3
  • 1
    The **parameter** `array` of function `Help` is actually an `int*`. – Anoop Rana Mar 09 '22 at 16:46
  • @AnoopRana isnt it global space too? – Jastcher Mar 09 '22 at 16:47
  • In main, array refers to the global variable. In Help, the global array has been shadowed (hidden) by the local variable of the same name in the function declaration. – jarmod Mar 09 '22 at 16:47
  • @Jastcher Doesn't matter. `Help` gets the array by parameter, it gets decayed to a pointer. It doesn't try to refer to the global variable, only to its parameter. – Yksisarvinen Mar 09 '22 at 16:49
  • 1
    [Compilers will warn for this.](https://gcc.godbolt.org/z/rMWo5K5Mx) (They'll also warn for the name shadowing if that's enough of a concern to enable it.) – chris Mar 09 '22 at 16:50
  • @Jastcher You are using a wrong function!:) Use a function where the array size is not being changed.:) – Vlad from Moscow Mar 09 '22 at 16:54
  • Side note: in recent C++ Library implementations you'll find `std::size` which does the `sizeof(array) / sizeof(int)` for you (albeit through completely different means) as well as being able to consume all manner of library containers so you can generalize your code more effectively. It still can't compute the size of a decayed array, though. – user4581301 Mar 09 '22 at 17:27

0 Answers0