0

I defined an 2d array in my code same:

double DownSide[][3]={
{0,10,10},
{0,10,10},
{0,10,10},
{0,10,10}
}; 

and send this array in a function:

ProcessImage(DownSide);

and in that function i give parameter same:

void ProcessImage(double DownSide[][3])

In this function, i want to calculate number row of this array. when i use this code:

sizeof(DownSide)/sizeof(DownSide[0])

the result show 0. but when i use this in main function, when i define array, i see correct number 4. Why when i use this code in function see 0? How can i find number rows of input array in function?

narges
  • 681
  • 2
  • 7
  • 26
  • 5
    This is precisely why you should *not* use the `sizeof` trick to get the number of elements in an array. In `main`, `DownSide` is an array. Inside `ProcessImage`, it is not an array, but a pointer! This is a subtlety of passing arrays into functions. I'm also fairly sure it is a duplicate question, so give me a minute to find one with a good answer... – BoBTFish Apr 25 '17 at 07:18
  • You cannot calculate the size of an array parameter inside a function. The parameter "decays" to a pointer to int[3]. The size information has to be implicit (e.g. a fully specified array) or come from outside, i.e. another parameter. – Yunnosch Apr 25 '17 at 07:18
  • If the DownSide of ProcessImage is declared as array, then it decays into pointer after compilation. You should declare the type of DownSide in ProcessImage as double (DownSide&)[][3]. – Jun Ge Apr 25 '17 at 07:21
  • In C++, it is usually better to avoid raw arrays at all, and instead use [`std::array`](http://en.cppreference.com/w/cpp/container/array) or [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). – BoBTFish Apr 25 '17 at 07:23
  • I am early in c++, Could you say me the solution in full code? – narges Apr 25 '17 at 07:26
  • 1
    @narges First forget about the 2d array, and use a simple `std::array` or `std::vector`, then pass that into a function *by reference* and print out the contents. – BoBTFish Apr 25 '17 at 07:30

0 Answers0