Array as parameter

I was wondering which one is best when I pass an array as a parameter?

void function(int arr[]) {...};

or

void function(int* arr) {...};

Could you tell me your reason? and what book can you name? Thank!

+5
source share
6 answers

Since this question is marked I would use neither. If you must use this, both are equivalent.

But since you are using C ++, it is better to use std::vectorfor such tasks

void function(std::vector<int> &arr) {...}

or if you do not modify the array / vector

void function(const std::vector<int> &arr) {...}
+4
source

If you just want to pass any array (including dynamically allocated), they are equivalent.

If your function requires a real array of fixed size, you can do this:

template <size_t N>
void function(char (&str)[N]) { ... }
+3
source

.

# 1 ( ), , .

+1

,

void function(int arr[]) {...};

void function(int* arr) {...};

const, const. [] , . , , const, , , [].

std::vector std::array, , .

+1

:

void function(type_t* array, int amountOfElts, int arrayAllocatedElts);

(, ) . , , strlen .

Using the [] option in function arguments is confusing in my opinion and should be avoided. But I do not think this is an agreement.

0
source

Depending on the level of abstraction you want to provide, you have to choose between Olaf's approach or what STL uses at a high level:

template <class Iter>
void function(Iter first, Iter last)
{
    // for example, to get size:
    std::size_t size = std::distance(first, last);
    // for example, to iterate:
    for ( Iter it = first; it != last; ++it )
    {
        // *it to get the value, like:
        std::cout << *it << std::endl;
    }
}

Thus, you can use this function not only for arrays, but also for various types of STLs: vectors, lists, queues, stacks, etc.

int tab[4] = {1,2,3,4};
function(tab, tab+4);

std::vector<int> vec;
// fill vector with something
function(vec.begin(), vec.end());
0
source

All Articles