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.
3
  • 1
    Use std::vector or std::array. Commented Mar 7, 2016 at 9:01
  • Hi Jarod42, as much as I would love to, I can't use those particular types for the exercise I'm working on. Commented Mar 7, 2016 at 9:02
  • Whenever you post code which has an error, please post the error message you get - sometimes this is incredibly useful to people trying to answer your question. Commented Mar 7, 2016 at 9:04

2 Answers 2

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]... }
Sign up to request clarification or add additional context in comments.

Comments

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>.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.