Course Content
C++ Functions
C++ Functions
Passing Static Array as an Argument of the Function
In C++, a static array is an array whose size is determined at compile time and remains constant throughout the program's execution.
Like values with simple data types, we can pass arrays as function arguments!
Pass 1-dimensional array as an argument
To pass a 1-dimensional array as an argument of the function, we have to use []
brackets after the variable name inside the function signature:
main
#include <iostream> // Function to process a 1-dimensional static array void processArray(int arr[], const int size) { for (int i = 0; i < size; ++i) std::cout << arr[i] << " "; // Print each element of the array std::cout << std::endl; } int main() { const int SIZE = 5; int oneDimArray[SIZE] = {1, 2, 3, 4, 5}; // Initialize a 1-dimensional static array std::cout << "Original Array: "; processArray(oneDimArray, SIZE); // Call the function to process the array }
Pass a 2-dimensional array as an argument
Passing a 2-dimensional array is very similar to passing a 1-dimensional array: we have to use the [][]
after the variable name.
But there is one important difference: in C++, you cannot directly pass a 2D array using the syntax datatype arrayName[][]
as a function argument.
When you pass a 2D array to a function, you need to specify the size of at least one array dimension inside the [][]
brackets. This is because C++ requires knowing the size of the dimension to calculate memory offsets when accessing elements in the array properly.
main
#include <iostream> // Function to process a 2D array with a specific number of rows void processMatrix(int matrix[][3], const int rows) { // Iterate through each row for (int i = 0; i < rows; ++i) { // Iterate through each column (assuming 3 columns in this case) for (int j = 0; j < 3; ++j) { std::cout << matrix[i][j] << " "; // Print each element of the matrix } std::cout << std::endl; // Move to the next line after processing each row } } int main() { const int ROWS = 2; // Number of rows in the 2D array int twoDimArray[ROWS][3] = {{1, 2, 3}, {4, 5, 6}}; // Initialize a 2D array std::cout << "Original Matrix:" << std::endl; processMatrix(twoDimArray, ROWS); // Call the function to process the matrix, passing the number of rows }
Since we need to specify at least one of the array dimensions (it doesn’t matter which), the signature of this function can also look like this:
Specify only number of rows
or
Specify both number of rows and columns
When we call the function inside the main()
block, we use the name of an array as an argument without any additional operators.
Everything was clear?