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";
}
}
int a[3]is an array;.int* ais a pointer. An array will decay to a pointer, but regardless an array is not a pointer. What you are doing wrong is you are not using astd::vector.make3()is only passed the address of the first element of the array passed bymain(). The function has no way in standard C++ to obtain the number of elements in that array. If you need to obtain the size (number of elements) you need to pass it in some way (e.g. as an additional argument) or, as Elijay said, usestd::vector(which is a data structure with member function, so you can obtain the size). If you can't usestd::vector, must pass a pointer, but you can't pass the size somehow, there is NO WAY to get the size.std::vectorwhich is an excellent replacement. However for these specific use cases (known fixed size) there is alsostd::array.