why does for each (marked as //)in this code not work? i dont understand. is it because q is pointing to p which is data in heap so in main we cant access it?
The pointer q is merely the address of an int. Given q and no supplemental information, there is no way to determine whether q points to a single int or to the first element of an array, and even if we assume that it points the first element of an array, there is no way to learn the size of the array. (Again, without extra information: the compiler is not smart enough to realize that size is the array size.)
Try:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <vector>
std::vector<int> array(int size)
{
return std::vector<int>(size, 1);
}
int main()
{
for (auto i: array(10)) std::cout << i << ' ';
}