I was wondering which one of these is the best when I pass an array as parameter?
void function(int arr[]) {...};
or
void function(int* arr) {...};
Could you tell me your reason? and which book you might refer to? Thanks!
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name. In C, when we pass an array to a function say fun(), it is always treated as a pointer by fun(). The below example demonstrates the same.
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
Passing array of objects as parameter in C++ It can be declared as an array of any datatype. Syntax: classname array_name [size];
The general syntax for passing an array to a function in C++ is: FunctionName (ArrayName); In this example, our program will traverse the array elements.
Since this question is tagged c++, I would use neither. If you must use this, both are equivalent.
But since you use C++, a better approach is to use a std::vector
for such tasks
void function(std::vector<int> &arr) {...}
or, if you don't modify the array/vector
void function(const std::vector<int> &arr) {...}
If you just want to pass any array (including dynamically allocated), they are equivalent.
Should your function require an actual fixed-size array, you could do this:
template <size_t N>
void function(char (&str)[N]) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With