Sitemap
Malinda Gamage

Malinda Gamage

Backend Software Engineer @ X-Venture | C++ | Java | Python | MSc in Information Technology | BSc in Manufacturing & Industrial

Mastering Array Passing in C++ Functions: A Comprehensive Guide 🚀🧵

5 min readFeb 4, 2025

--

Arrays are a fundamental part of C++ programming. Understanding how to pass arrays to functions and control their behavior is critical for building modular, efficient, and error-free programs. In this blog, we’ll explore how arrays are passed to functions, the role of the array name as a pointer, and how to use the const keyword to prevent accidental modifications. By the end, you'll feel confident handling arrays in C++ functions!

🌟 The Basics: Passing Arrays to Functions

When you pass an array to a function in C++, you’re not passing a copy of the array. Instead, you pass the address of the first element of the array. This means:

  1. Efficient: No large arrays are copied, which saves memory.
  2. Potential for Modification: Since you pass the actual location of the array, the function can modify the original array.

Here’s a simple example:

#include <iostream>
using namespace std;

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int myNumbers[] = {1, 2, 3, 4, 5};
printArray(myNumbers, 5); // Passing the array and its size
return 0;
}

How It Works:

  • The function printArray receives the address of the first element (myNumbers[0]).
  • Since an array name evaluates to its address, the array’s memory is shared between main and printArray.
  • But there’s a caveat: C++ does not know how many elements are in the array, which is why we also pass the array size as a parameter.

🔑 Why Passing Array Size Is Necessary

Arrays in C++ don’t carry size information. Unlike vectors or strings, arrays rely on the programmer to specify their size explicitly.

What Happens If You Don’t Pass the Size?

The function will have no way of knowing where the array ends, leading to undefined behavior. For example:

void printArray(int arr[]) {
for (int i = 0; i < 100; i++) { // Assuming 100 elements
cout << arr[i] << " "; // May access invalid memory
}
}

This is why you must pass the size explicitly:

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

🛑 Arrays Are Passed by Address, Not by Copy

When you pass an array to a function, you’re not passing the entire array. You’re only passing the address of the first element. Therefore, any changes made to the array inside the function will affect the original array.

Example: Modifying an Array Inside a Function

#include <iostream>
using namespace std;

void setArrayToValue(int arr[], int size, int value) {
for (int i = 0; i < size; i++) {
arr[i] = value; // Modify the original array
}
}
int main() {
int myScores[] = {100, 98, 90, 86, 84};
setArrayToValue(myScores, 5, 100); // Set all elements to 100
for (int score : myScores) {
cout << score << " "; // Prints 100 five times
}
return 0;
}

Explanation:

  • The array myScores is passed by address.
  • The function setArrayToValue modifies each element of the original array directly.
  • When we print the array in main, we see that the original array has been modified.

🔒 Protecting Arrays with const

What if you want to prevent the function from modifying the array? C++ allows you to do this by using the const keyword.

Why Use const?

  • Prevent unintended changes to arrays when you only intend to read them.
  • Help the compiler catch errors when someone accidentally tries to modify the array.

Example: Using const

#include <iostream>
using namespace std;

void printArray(const int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int myNumbers[] = {10, 20, 30, 40, 50};
printArray(myNumbers, 5);
// Uncommenting the line below would cause a compiler error:
// arr[0] = 100;
return 0;
}

What Happens When You Use const?

  • The function printArray cannot modify the array elements.
  • If you accidentally include a statement that modifies the array, the compiler will throw an error.

Example error message:

error: assignment of read-only location

⚠️ Understanding Common Pitfalls

  1. Forget to Pass Array Size: If you forget to pass the size of the array, you risk accessing out-of-bounds memory.
  2. Unintended Modification: If you don’t use const when you should, a function might unintentionally change the array.
  3. Pass Large Arrays Efficiently: Although arrays are passed by address, sometimes passing large arrays can still have performance implications. Consider using pointers or references when appropriate.

🚀 Visualizing What Happens in Memory

Let’s visualize how the function call works with an example:

int myScores[] = {100, 98, 90, 86, 84};  // Array declared in main

When you pass myScores to a function, only the address of the first element (myScores[0]) is passed. Let’s assume the memory location for myScores[0] is 2000:

Press enter or click to view image in full size

In the function:

  • The address (2000) is passed, not the entire array.
  • The function accesses the array elements using their offsets (e.g., arr[1] accesses address 2004).

✅ Best Practices for Passing Arrays

  1. Always pass the array size to avoid accessing out-of-bounds memory.
  2. Use const for read-only arrays to prevent unintended modifications.
  3. Use descriptive parameter names to improve code readability and maintainability.

🏁 Conclusion

Passing arrays to functions in C++ can be powerful but tricky if not handled correctly. The key takeaways are:

  • Arrays are passed by address, not by copy.
  • Use const when you don’t want the function to modify the array.
  • Always pass the array size along with the array.

Understanding these fundamentals will make your programs more robust, readable, and error-free. Stay tuned for the next topic — pass by reference — which builds on this concept and allows for even more control when passing data to functions.

Get Malinda Gamage’s stories in your inbox

Join Medium for free to get updates from this writer.

by : Malinda Gamage

--

--

Malinda Gamage
Malinda Gamage

Backend Software Engineer @ X-Venture | C++ | Java | Python | MSc in Information Technology | BSc in Manufacturing & Industrial