Menu
Coddy logo textTech

Arrays And Functions

Part of the Fundamentals section of Coddy's C++ journey — lesson 62 of 74.

Arrays cannot be passed directly to functions as complete arrays. When you try to pass an array to a function, it "decays" into a pointer to its first element.

For example:

int numbers[5] = {1, 2, 3, 4, 5};
void processArray(int arr[]) {
	int size = std::size(arr);
}

std::size(arr) won't give you the actual array size. arr is actually a pointer here, not an array. Pointers will be learned in the next course.

This is why when passing arrays to functions, we typically need to pass the size as a separate parameter:

void processArray(int arr[], int size) {
    // Now we can safely work with the array using the size parameter
}

Here how to call the function:

int numbers[5] = {1, 2, 3, 4, 5};
processArray(numbers, 5);

Also it is not possible to return an array in a function:

int[] processArray(int arr[]) {
	return arr;
}

This is illegal. Instead you should use the * syntax:

int* processArray(int arr[]) {
	return arr;
}
int* newArr = processArray(arr);

The star (*) syntax refers to pointers which will discussed in the next course.

Cheat sheet

Arrays cannot be passed directly to functions - they "decay" into pointers to their first element.

When passing arrays to functions, you need to pass the size as a separate parameter:

void processArray(int arr[], int size) {
    // Work with array using size parameter
}

int numbers[5] = {1, 2, 3, 4, 5};
processArray(numbers, 5);

Arrays cannot be returned directly from functions. Use pointer syntax instead:

int* processArray(int arr[]) {
    return arr;
}
int* newArr = processArray(arr);

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals