Home c++ Array length in a C++ function

Array length in a C++ function

Author

Date

Category

How can I find out the length of the passed array (for the loop body) in the function body?

# include & lt; iostream & gt;
int myfunc (int arr [])
{
  int sum = 0, quantity = 0;
  for (int i = 0; i & lt; (length of array (pointer)); i ++)
  {
    if (arr [i] & gt; 0)
    {
      quantity ++;
      sum + = arr [i];
    }
  }
  return sum;
}
int main ()
{
  int a [70], b [80], c [65];
  std :: cout & lt; & lt; myfunc (a);
}

Answer 1, authority 100%

Your question is so popular that it even made it into the C FAQ: [1] , [2] .

The fact is that arrays in the parameters of functions “turn” into pointers. Therefore, your function declaration is no different from

int myfunc (int * arr)

You can check that in your function sizeof (arr) gives the size of the pointer (usually 4 or 8 on modern architectures).

A practical way out: pass the length of the array as a separate parameter.


Answer 2, authority 31%

There is nothing in C.

In C++, you can use a template function, in which the size will become a template parameter. In any case, you shouldn’t do this, as it will not allow using the function with dynamic arrays.

http://ideone.com/HNxwr8

# include & lt; iostream & gt;
using namespace std;
template & lt; typename typed, size_t n & gt; void f (typed (& amp; a) [n])
{
  for (size_t q = 0; q & lt; n; ++ q)
    cout & lt; & lt; a [q] & lt; & lt; '';
  cout & lt; & lt; '\ n';
}
int main ()
{
  int a [] = {1, 2, 3, 4, 5};
  char s [] = "Just a string";
  double b [] = {1.5, 2.75, 4};
  f (a);
  f (b);
  f (s);
  return 0;
}

Answer 3, authority 31%

In the body of the function, you can find out the length of the array from the argument passed in the neighborhood:

int foo (int * buffer, const size_t bufferSize) {...}

More interesting is the question of how to return an array from a function . For these purposes, C++ 11 introduced std :: array , which is nothing more than a wrapper over ordinary static buffers, which, among other things, contains a size () method.


Answer 4, authority 23%

Alternatively, use a vector and get the size of the array using arr.size ()


Answer 5

I faced this problem today, but still found a way out.
The length of an array can be determined using this function:

int getLength (char text []) {
  int arrayLength = 0;
  for (int i = 0; text [i]; i ++) {
    arrayLength ++;
  }
  return arrayLength;
}
int main (void) {
cout & lt; & lt; getLength ("Symbols");
}

Also, to return an array to a function, just write
char * before the function name.

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