//how we are able to access array with subscipt a[i]
a[i]
is the same thing as *(a + i)
.
As it is now, your print
will only work for arrays of the exact size 3, so:
- If the array happens to have more than 3 elements, some elements will not be printed.
- If it happens to have less than 3, you'll access whatever is in memory behind the array, which is undefined behavior (translation: very bad!).
The size of the array gets "forgotten" when you pass the array to a function, so either explicitly pass the size to make the function reusable for arrays of all sizes (reusability is the point of having functions after all!)...
void print(int const* a, size_t a_size) {
for (size_t i = 0; i < a_size; ++i) // size_t is the appropriate type here, not int.
std::cout << a[i] << std::endl; // Use std::endl to be able to discern where teh current number ends and the next starts!
}
// ...
int arr[3] = {1, 2, 3};
const size_t arr_size = sizeof(arr) / sizeof(arr[0]);
print(arr, arr_size);
...or do it in the C++ way and use std::vector
...
void print(const std::vector<int>& a) {
for (const auto& s : a) // The new C++11 "for each" syntax.
std::cout << s << std::endl;
}
// ...
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
print(a);
...or even make it generic...
template <typename T>
void print(const std::vector<T>& a) {
for (const auto& s : a)
std::cout << s << std::endl;
}