There's no getting around the fact that C++ was originally just a front end for C and, as such, carries a fair amount of baggage from the original language. Such as many things in the <cXXX>
headers, and the behaviour of many operations, like array decay(a).
If you want a more convenient array type, C++ has such a beast in std::vector
. If you pass that around, you will not be subject to the decay you may see when using the more low-level memory allocation methods. See, for example:
#include <iostream>
#include <vector>
void someFunction (const std::vector<int> &myVec) {
std::cout << myVec.size() << std::endl;
}
int main() {
std::vector<int> myVec({ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9, 0 });
std::cout << myVec.size() << ' ';
someFunction(myVec);
}
which outputs 13 13
, showing that the size is the same outside and inside the function (it's also the size in elements rather than bytes as given bt sizeof
, the former usually being a far more useful measure).
When mentoring or training C++ programmers, I always warn them about being a "C+" programmer, one who was raised on C and never really made the full transition to C++ (things like continuing to use raw arrays instead of vectors, rolling you own data structures when perfectly adequate ones are in the standard library, using malloc/free
or printf
, and so on).
You would be wise thinking of C and C++ as related but totally different languages, and adopting the C++ way of thinking as much as possible.
(a) Interestingly, your specific question does not have an array decaying into a pointer. The new
call actually returns a pointer directly so there's no decay involved.
Where you would see decay is in something like:
void someFunction (int x[]) {
// Pointer to first element here, size is int-pointer-size.
std::cout << sizeof(x) << std::endl;
}
:
// Array here, size is 13 * int-size.
int xyzzy[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9, 0 };
std::cout << sizeof(xyzzy) << std::endl;
someFunction(xyzzy);