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 << ",";
    }
}

1 Answers1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Maybe add an example how `template ` could be helpful here? – Kijewski Jun 27 '17 at 13:15
  • 1
    @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 – 463035818_is_not_an_ai Jun 27 '17 at 13:18
  • @tobi303 e.g. https://ideone.com/qfL34G – Kijewski Jun 27 '17 at 13:21
  • @kay and? I know that nice trick, but it doenst work for dynamically allocated arrays – 463035818_is_not_an_ai Jun 27 '17 at 13:22
  • `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 –  Jun 27 '17 at 14:39
  • @Nuwan722 `int arr[]` syntax is identical to `int *arr`. You need a template to capture array size. See ideone link posted by kay above. – Sergey Kalinichenko Jun 27 '17 at 14:44