- Can I pass arrays to functions just as I would do with primitives such as int and bool?
- Can I pass them by value?
- How does the function know of the size of the array it is passed?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Numpy matrix of coordinates
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
void f(int a[]);
and call it like this:int myArr[size]; f(myArr);
C-style arrays behave very strangely when passed into functions. For fixed-sized arrays, I would recommend
std::array<int, 10>
instead, which can be passed by value like built-in types. For variable-sized arrays, I recommendstd::vector<int>
, as suggested in other answers.You can pass an array, but you must pass the size along with it if you want to know it for sure:
Arrays are always passed by reference and the function can be written one of two ways:
or
When you pass an array to a function the function in essence receives a pointer to that array, as seen in the second example above. Both examples will accomplish the same thing.
Yes, you can pass them the same as primitive types. Yes, you can pass by value if you really wanted to with some wrapper code, but you probably shouldn't. It will take the size of the function prototype as the length - which may or may not match the incoming data - so no it doesn't really know.
Or!
Pass a reference or const reference to a vector and be safer and have the size info at your finger tips.
You can pass a
std::vector
and similar well-designed object by value (though this is rather uncommon). Typically, you pass by reference or const reference.A C/C++ array, as in
is always passed by reference. Also, the function can not determine the true size of the argument passed in by the caller, you have to assume a size (or pass it as separate parameter).
Yes, but only using pointers (that is: by reference).
No. You can create classes that support that, but plain arrays don't.
It doesn't. That's a reason to use things like
vector<T>
instead ofT *
.Clarification
A function can take a reference or pointer to an array of a specific size:
I'm pretty sure this is not what the OP was looking for, however.