3
#include <iostream>
void ArraySize(int arrMyarr[])
{
    std::cout << sizeof(arrMyarr) << '\n';
}

void ArraySize1(int *arrMyarr)
{
    std::cout << sizeof(arrMyarr) << '\n';
}

int main()
{
    int arrTemp[] = { 122, 11, 22, 63, 15, 78, 143, 231 };
    std::cout << sizeof(arrTemp) << '\n';
    ArraySize(arrTemp);
    ArraySize1(arrTemp);
    return 0;
}

output: 32 4 4

Does below two declarations of functions are same?

void ArraySize(int arrMyarr[]);

void ArraySize1(int *arrMyarr);

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
DevMJ
  • 2,810
  • 1
  • 11
  • 16

4 Answers4

6

Does below two declarations of functions are same?

Yes, completely. Arrays decay to a pointer to their first element when passed like that which is why you're seeing 4. To prevent this, either use std:vector::size() or std::array (C++11) for a compile time sized C-like array.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

Does below two declarations of functions are same?

void ArraySize(int arrMyarr[]);

void ArraySize1(int *arrMyarr);

Yes, exactly the same. In the context of function parameter, arrMyarr[] in converted to *arrMyarr implicitly. This is so-called "array decays to pointer".

artm
  • 17,291
  • 6
  • 38
  • 54
1

Yes the above two syntaxes for the functions are same

In both the cases we passing reference to the first element of an array in C++ i.e. arrMyarr .

Even if you were to put a number inside the brackets: in void ArraySize(int arrMyarr[10]) the 10 is completely ignored

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

Note that if you'd like to see the real size, you can do:

template<int N>
void ArraySize2(int (&arrMyarr)[N])
{
    std::cout << sizeof(arrMyarr) << '\n';
}

which shows 32.

(but also note that the template is instantiated for every different array size it is called with)

Can be also templatized for the type (to end up with the so-called "size of array" template).

EmDroid
  • 5,918
  • 18
  • 18