How do I pass an array to a function?

You need the array to be an input parameter.

void f (int &heap[])
{

}

The compiler swears at the code above.

Author: Abyx, 2012-08-15

4 answers

I hope it will be clearer now.

#include <stdio.h>

void
elem2 (int a[], int v)
{
  a[2] = v*v;
}

int
main ()
{
  int a[3] = {1,2,3};

  elem2(a,10);

  return printf("elem[2] = %d\n",a[2]) == EOF;
}

c:/Documents and Settings/avp/src/hashcode $ gcc a.c
c:/Documents and Settings/avp/src/hashcode $ ./a
elem[2] = 100
c:/Documents and Settings/avp/src/hashcode $ echo $?
0
c:/Documents and Settings/avp/src/hashcode $

If something is not clear, ask.

 7
Author: avp, 2012-08-15 10:29:30

The correct array reference syntax is

void f(int (&arr)[123]) {}

If the size of the array is unknown, you can use the template:

template<std::size_t N> void f(int (&arr)[N]) {}

If what is passed to the function is not an array, but a pointer (i.e. not T[N] a T*), then the function must accept a pointer, and the size must be passed as an additional parameter or something else.

void f(int* ptr, std::size_t n) {}

However, this is a very unreliable solution, there is no guarantee that the correct array size will be passed, or that ptr is not equal to nullptr.
The correct way to do this is to use span<T> from C++ Core Guidelines

void f(gsl::span<T> arr) {}

Also, instead of the T[N] array, you can pass a reference to std::array

void f(std::array<T, N>& v) {}

And instead of a dynamic array, use std::vector:

void f(std::vector<T>& v) {}
-- или --
void f(const std::vector<T>& v) {}
 10
Author: Abyx, 2016-03-04 11:14:44

Try passing a pointer to an array, if it is one-dimensional, then:

void f(int* arr) { }

The fact is that a pointer to an array is passed to the function. You can do whatever you want with the array inside the function, the changes will be visible from outside. The array cannot be passed by value.

 7
Author: ivan milyutkin, 2012-08-15 10:03:22

Two ways to pass an array to a function:

void foo (int* arr) {
....
}

Or

void foo (int arr[]) {
.....    
}

But with both methods, as mentioned, it makes sense to pass the size of the array as the second (or other) parameter, or somehow fix its end in the array itself.

However, in C++, it is still better to use the vector container or (in the case of static array size determination) array (from C++11 or boost.array)

 6
Author: skegg, 2012-08-15 10:36:52