Menu
CoddyTech

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) does not compile here, because arr is actually a pointer, not an array, and a pointer does not store the size of the 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.

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

Practice on your own: Online C++ compiler