A raw array only supports the range-based for syntax if the visible declaration includes the number of elements, i.e. int arr[3]
in the first case and int* prt
in the second case. In the first case this is given (but still you should prefer std::array
if possible), but not in the second case you allocate memory on the heap and the information about the size is gone. You can circumvent this, if you simply use std::array
rather than the raw array.
Since the pointer was dereferenced, the types should be the same.
Taking a closer look under the hood, the reason for this is, that in the first case you have an array and in the second case you have a pointer, which is NOT even the same type.
This misinterpretation of pointer and array equaliuty keeps to be broadcasted over C++ tutorials, but this is wrong. This might be due to the fact, that when passing an array to a function taking a pointer of that type, the array decays to a pointer, known as array-decay.
Can I make it work with a small change
Yes you can. Use std::array
or st::vector
which will make it look like that for std::array
:
#include <iostream>
#include <array>
int main()
{
std::array<int, 3>* ptr = new std::array<int, 3>;
for(int& value : *ptr )
std::cout << "success" << std::endl;
}
For brevity I did not include the delete for the pointer which you should always do.
However, if you allocate memory on the heap, it is almost always best to use std::vector
as deallocation will be taken care for automatically. The program would than read:
#include <iostream>
#include <vecor>
int main()
{
std::vector<int> vec(3);
for(int& value : vec)
std::cout << "success" << std::endl;
}