0

if I create a new int array object using new like below:

int *array = new int[20];

and fill the array with some integers, then attempting to scan through that array with a for-each loop will throw me an error:

for (int x : array)  // error

why does this happen and how can I fix it? I tried playing around with the referencer and address notations (* and &) but every combination I tried fails.

ex.

for (int &x : *array)  // does not work either.
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Manuel
  • 2,143
  • 5
  • 20
  • 22

2 Answers2

6

array is not an array, but a pointer, which can't be used for Range-based for loop, because there's no information about the size of the "array", the begin and end of the "array" can't be deduced.

range_expression - any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined, see below) or a braced-init-list.

You might make it real array, (or use std::array instead of the raw array)

int array[20];
for (int x : array) { processing with x... }

Or write the loop manually:

for (int i = 0; i < 20; i++) { processing with array[i]... }
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

in for (int x : array), it requires that begin(array) and end(array) are valid. which is not for int*.

it would work for int array[20], std::vector, std::array<int, 20>.

Jarod42
  • 203,559
  • 14
  • 181
  • 302