-5

Here I'm trying to user c++11 range base loop for tow integer arrays. one declared using new keyword and other not.

#include <iostream>
#include <stdlib.h>

#define ARRAY_LENGTH 100    

int main()
{
          int* heap_array = new int[ARRAY_LENGTH];
          int stack_aray[ARRAY_LENGTH];

          for(int i=0; i < ARRAY_LENGTH; i++)
          {
            int val = (rand() % ARRAY_LENGTH) + 1;
            heap_array[i] = val;
            stack_array[i] = val;
          }

          for(int& i : stack_array){ std::cout << i << std::endl;}
          for(int& i : *heap_array){ std::cout << i << std::endl;} // compile error

          delete[] heap_array;
          return 0;
}

Why range base loop doesn't work for the array declared with new keyword? my view is it doesn't matter heap or stack both are heap_array & stack_array are pointers to the first element.

Nayana Adassuriya
  • 23,596
  • 30
  • 104
  • 147
  • 6
    `stack_array` is an array. `heap_array` is just a pointer. – Ry- Aug 21 '16 at 09:44
  • @Ryan: `stack_array` not a pointer? – Nayana Adassuriya Aug 21 '16 at 09:46
  • 1
    http://stackoverflow.com/questions/1461432/what-is-array-decaying Anyways, `*heap_array` is `int`, so what did you expect from it? And please, look at the docs before asking to see that there is no magic involved and that range based for is a mere syntactic sugar that uses `std::begin` and `std::end` to know the range. And `std::end` with a pointer does not make sense. – LogicStuff Aug 21 '16 at 09:48
  • 2
    No. Arrays decay to pointers when necessary, but they're not the same thing. Take `sizeof stack_array` (`ARRAY_LENGTH * sizeof(int)`) compared to `sizeof heap_array` (`sizeof(int*)`), for example. – Ry- Aug 21 '16 at 09:48
  • @NayanaAdassuriya, `stack_array` is an array, not a pointer; it can be used like a pointer sometimes, because, in certain contexts, an array-to-pointer conversion may be performed – chill Aug 21 '16 at 09:50
  • @LogicStuff : thank you, your link open-up my eyes. – Nayana Adassuriya Aug 21 '16 at 10:00
  • 1
    Just use `std::array` or `std::vector` instead. – Jesper Juhl Aug 21 '16 at 10:09

1 Answers1

4

Your heap_array isn't really an array but a raw pointer to an int. A raw pointer does not know anything about the number of elements allocated.

Frank Puffer
  • 8,135
  • 2
  • 20
  • 45