Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating array size inside function? [duplicate]

Tags:

c++

#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);

like image 935
DevMJ Avatar asked May 05 '26 01:05

DevMJ


2 Answers

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.

like image 160
Hatted Rooster Avatar answered May 07 '26 11:05

Hatted Rooster


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".

like image 21
artm Avatar answered May 07 '26 11:05

artm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!