Home c++ How to find out the size of the array passed to the...

How to find out the size of the array passed to the function?

Author

Date

Category

It is necessary to determine the size of the array passed to the function. Tried like this:

void foo (int * Array)
{
  const unsigned int SIZE = sizeof (Array) / sizeof (int);
}

but SIZE retains 1, regardless of the size of the array. You can, of course, pass the size to the function along with the array, but maybe there is a more elegant solution?

P.S .: By the way, I noticed something strange. Launched this program through Visual Studio and Qt. In VS, SIZE stores 1, while in Qt 2.


Answer 1, authority 100%

You have a function parameter foo declared as a pointer of type int *

void foo (int * Array);
     ^^^^^^^^^^

Hence, inside the function, the expression

sizeof (Array) / sizeof (int)

is equivalent to

sizeof (int *) / sizeof (int)

If, for example, the size of a pointer, that is, of type int * , is 8 bytes, and the size of type int is 4 bytes, then you will end up with 2. If while the size of the int type is also 8 bytes (64-bit OS), you will end up with 1.

But even if you declare this function as

void foo (int Array []);

or even so

void foo (int Array [10]);

anyway, the function parameter is implicitly converted to a pointer to an array element. That is, these two function declarations declare the same function and are equivalent to the following declaration

void foo (int * Array);

So inside the function, you will be dealing with a pointer again.

When passing an array by value, you should also declare a second parameter that specifies the size of the array.

Or the array must have some boundary element with a unique value, which can be used to determine the number of actual elements, as is the case, for example, with strings, when strings are null terminated, that is, the character '\ 0' .

That is, in general, you should declare a function as

void foo (int * Array, size_t n);

where n is the size of the array.

Another approach is to declare the parameter as an array reference. In this case, the length of the array will be known inside the function. For example

void foo (int (& amp; Array) [10])
{
  const size_t = sizeof (Array) / sizeof (* Array);
}

The disadvantage of this declaration is that this function can only deal with arrays given in its size parameter.

To work around this limitation, you can declare a templated function. For example,

template & lt; size_t N & gt;
void foo (int (& amp; Array) [N])
{
  const size_t n = N;
}

In this case, the compiler, using the template, will create as many functions as arrays of different lengths were used as an argument.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions