dimanche 21 août 2016

why range base loop doesn't work for arrays in heap, but works for the arrays in stack

int* heap_array = new int[ARRAY_LENGTH];

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

      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;

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.

Aucun commentaire:

Enregistrer un commentaire