Is this normal?
Yes.
In C++, an array will decay to a pointer at any opportunity. C++ inherited this convenience behavior from C.
It makes thinking about arrays as-if they were the same as pointers. But they are not.
In C++ a pointer can point to nothing (nullptr
), or point to an object, or point to an array of objects. The pointer is oblivious of whether it points to an object or an array of objects.
(Or be dangling, or be uninitialized, or be some arbitrary value. These should be avoided.)
If not, what am I doing wrong?
You are not using std::vector
.
Since, in the comments, you say that you cannot use a std::vector
, then you'll need to pass in the length of the array as a std::size_t
parameter along with a pointer to the array.
But you also say you cannot pass in the length of the array. So then you will need to use an array reference rather than a pointer.
Also, C++17 has std::size(a)
which can be used instead of sizeof(a)/sizeof(a[0])
.
#include <cstddef>
#include <iostream>
using std::cout;
using std::size_t;
template <size_t N>
void make3(int(&a)[N]) {
for (size_t i = 0; i < N; ++i) {
a[i] = 3;
}
}
int main() {
int a[3] = { 0, 1, 2 };
make3(a);
int* b = a;
for (size_t i = 0; i < sizeof(a)/sizeof(a[0]); ++i) {
cout << *(b + i) << "\n";
}
}