Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as parameter

Tags:

c++

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!

like image 335
JASON Avatar asked Feb 18 '13 08:02

JASON


People also ask

Can we send an array as a parameter to a function?

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.

Can an entire array be passed as a parameter?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

How do you pass an array of objects as a parameter?

Passing array of objects as parameter in C++ It can be declared as an array of any datatype. Syntax: classname array_name [size];

How do you pass an array as a parameter to a function C++?

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.


2 Answers

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) {...}
like image 68
Olaf Dietsche Avatar answered Oct 13 '22 22:10

Olaf Dietsche


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]) { ... }
like image 22
Angew is no longer proud of SO Avatar answered Oct 13 '22 23:10

Angew is no longer proud of SO