You can't use range-based for
to iterate over an array of unknown bound or "over" a pointer. A compiler doesn't know where to stop.
Assuming that for some reason arr
parameter is fixed to be void*
, you can pass the size explicitly:
void test(void* arr, std::size_t size) {
int* arr2 = static_cast<int*>(arr);
while (size-- > 0)
std::cout << *arr2++ << std::endl;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
test(arr, 5);
}
But this is an example of a bad code. Don't do it unless you have a good reason.
If you want to use a range-based for loop, in C++20 you'll be able to use use std::span
:
void test(void* arr, std::size_t size) {
int* arr2 = static_cast<int*>(arr);
std::span span(arr2, size);
for (int num : span)
std::cout << num << std::endl;
}
Before that you can use a self-made workaround:
template<typename T>
class my_span {
public:
my_span(T* first, std::size_t size) :
first_(first), size_(size) {}
T* begin() const {
return first_;
}
T* end() const {
return first_ + size_;
}
private:
T* const first_;
const std::size_t size_;
};
void test(void* arr, std::size_t size) {
int* arr2 = static_cast<int*>(arr);
my_span span(arr2, size);
for (int num : span)
std::cout << num << std::endl;
}