Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ for-each loop with array allocated on the heap

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(0); cin.tie(0);
    auto arr = new int[5];
    // int arr[5] = {1, 2, 3, 4, 5};
    for (auto i: arr){
        cout << i << ' ';
    }
}

Why isn't this working? I am getting a compile time error saying this.

C.cpp: In function 'int main()':
C.cpp:8:15: error: 'begin' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
     begin(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
C.cpp:8:15: error: 'end' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'
     end(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'

When I initialized array in commented way, it works fine. (obviously) So, I think problem is with new operator. But I don't understand what it is.

like image 543
avamsi Avatar asked Dec 04 '25 14:12

avamsi


1 Answers

new int[5] allocates an array of 5 elements and returns a pointer to the first element. The returned type is rvalue int*

int foo[5] is an array of 5 elements. The type of foo is lvalue int [5]

The range for loop requires it to know the size of the object it is iterating over. It can iterate over arrays, but it cannot iterate over pointers. Consider this code,

int foo[4];
for (int a : (int *)foo) {}

GCC 5.0 also produces an error "error: ‘begin’ was not declared in this scope" because the array was decayed into a pointer.

like image 170
user3427419 Avatar answered Dec 07 '25 04:12

user3427419



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!