You arrays have size 3, but you try to store 4 elements in them and access the fourth element at [3]
(which has undefined behaviour).
Make them bigger, either hardcoding 4 or making everything automatically adjust to the current length of the list of numbers you use to initialise inArray
:
int inArray[] = {1,2,3,4}; // automatically sized
int outArray[sizeof inArray / sizeof *inArray];
Then, your function signature should specify the array-of-int
of the arguments. There are many ways to do that:
void myFunction(const int inArray[], int outArray[]) // 1
void myFunction(const int* inArray, int* outArray) // 2
void myFunction(const int (&inArray)[4], int (&outArray)[4]) // 3
template <size_t N>
void myFunction(const int (&inArray)[N], int (&outArray)[N]) // 4
The first is clearly the simplest.
The second is equivalent, as when a caller passes array arguments they're allowed to decay to pointers, and that happens even for 1) as the array dimension can only be captured or enforced when accepting arrays by reference, as in the following cases...
The third additionally ensures the array parameters have exactly 4 elements (so suddenly you can't (easily) pass say an array of 10 elements and have it copy over only the first 4).
The fourth accepts any sizes of array, but if used from different calling code on different sized arrays it may create multiple copies of the myFunction
code, potentially using more memory for a larger program.
As you're function body hardcodes operations on elements [0]
to [3]
, it won't adjust to do things on elements further into larger arrays, but you have the option of using the N
value inside the function body to work out how many elements to operate on.