Izzo
Izzo

Reputation: 4928

Varying Sized Array as Function Input in C++

I'm currently working on a function that I wish to accept various array lengths as inputs. For example, let's say I have a function called 'sum'. Ideally, I would want to feed this function an array of ints that can vary in size (i.e. one call will sum [1, 2, 3, 4] and another call may sum [1, 1, 1].

What is the best practice for achieving this? I had attempted declaring a function as

 int sum(int array[]);

but this throws a compiler error saying that the length of the argument array must be specified.

Would it be better practice to use a reference to a pointer titled array along with a length specifier that would be used as iterator? As in

 int sum(const int*& array, int lengthArray);

With this approach, I assume it would be possible to get access to the values of the array, and then be able to cycle through elements using the length of the array as another argument. However, I am not confident if my logic regarding the pointer and reference is on track with 'good code'.

I don't have the means to try this until I get home from work, but the problem has been on my mind ever since it came up. So I thought I would pose the question regarding what the best practice is.

Any help is appreciated!

Upvotes: 0

Views: 64

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

In general I'd give the same advice, as @Cheers and hth. - Alf does.

However, I am not confident if my logic regarding the pointer and reference is on track with 'good code'.

The use of a reference isn't really needed, it would be sufficient to write

 int sum(const int* array, int lengthArray);

Use references for pointers where you want to change these from inside the function (e.g. for allocating memory).

Upvotes: 0

Sasha Pachev
Sasha Pachev

Reputation: 5326

You could use std::vector as was suggested, but if you do need to use the C array, you can do this:

int sum(int* array, unsigned int len) 

or just

int sum(int* array)

if you use a special value (e.g INT_MAX) to make the end of the array. In C array and pointer are essentially the same thing.

Upvotes: -1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

As a C++ beginner use std::vector for variable length arrays, and std::array for fixed size arrays.

Upvotes: 4

Related Questions