lundi 27 août 2018

Range based for loop for heap allocated arrays

Consider the following code which will cout success exactly three times:

int arr [3];

for(int& value : arr )
    std::cout << "success" << std::endl;

If I try to allocate array on the heap, there are problem. This code doesn't compile:

int* ptr = new int[3];

for(int& value : *ptr )
    std::cout << "success" << std::endl;

Since the pointer was dereferenced, the types should be the same. So I have some questions:

  • what is the fundamental difference between when I ask from the hardware in the two expressions. I'd like to understand why the latter don't make sense.
  • Can I make it work with a small change?

Aucun commentaire:

Enregistrer un commentaire