0

For ex. I have a function

void len(int *A){ // or we have its reference

// can I find the length of array here or
// we just need to pass the length along as the parameter

}
  • You can't. `A` is a pointer, not an array. Use `std::vector` instead of passing length explicitly unless you really have to. Also take a look at [`std::span`](https://en.cppreference.com/w/cpp/container/span) - it will be available in C++20. – Evg Nov 01 '20 at 07:38

1 Answers1

2

can I find the length of array here or we just need to pass the length along as the parameter

You can't find the length once the array has decayed into a pointer so one option is to supply the length as a parameter as you said yourself.

Another option is to not let it decay into a pointer:

template<size_t N>
void len(int(&A)[N]) {
    // N is the length
}

Or you could use a std::vector<int>:

void len(std::vector<int>& A) {
    // A.size() returns the length
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108