0

I tried to iterate through the following arr array . but Visual studio shows it has a error.

void printArray(int* arr)
{
    for (int i : arr)
    {
        cout << i << ",";
    }
}
3
  • Say you pass a random pointer to that. When do you expect the for loop to stop? That's not an array. If it ever was, it's been decayed to a pointer. Commented Jun 27, 2017 at 13:10
  • Voted to close because you didn't copy (or even read) the error message. How should the code know the dimensions of arr? Commented Jun 27, 2017 at 13:11
  • 2
    arr isnt an array but just a pointer to an int, what should be the end of the loop? Commented Jun 27, 2017 at 13:12

1 Answer 1

0

In your example arr is not an array, it is a pointer. Therefore, it is impossible to determine the number of items in your array from the pointer alone: this is the reason why APIs that take a pointer to array's initial element also take the number of elements in that array, for example:

void printArray(int *arr, size_t count)

Since the number of items in the array is unknown, arr cannot be used in a range loop.

You copy range data into std::vector to use it in a range loop:

void printArray(int *arr, size_t count) {
    for (int i : vector<int>(arr, arr+count)) {
        cout << i << ",";
    }
}

Demo.

However, passing std::vector in place of a pointer is a much better way of achieving the same effect with idiomatic C++ code.

Sign up to request clarification or add additional context in comments.

6 Comments

Maybe add an example how template <class T, size_t N> could be helpful here?
@kay afaik it wont help here, because it doesnt work for dynamically allocated arrays. Anyhow, once you have only a pointer to the first element there is no way to get the size from that pointer alone
@tobi303 e.g. ideone.com/qfL34G
@kay and? I know that nice trick, but it doenst work for dynamically allocated arrays
void Myalgo::printArray(int arr[]) { for (int i : arr) { cout << i << ","; } } I tried this way also not working . Instead of pointer i used array. But it is still shows error inside the for each loop
|