C++ Pass Array to a Function

πŸ“¦ C++ Pass Array to a Function

In C++, arrays are passed to functions by reference by default.
That means the function receives the address of the first element, so changes inside the function affect the original array.


πŸ”Ή 1. Basic Syntax

void functionName(dataType arrayName[], int size);

or

void functionName(dataType *arrayName, int size);

πŸ‘‰ Both are equivalent.


πŸ”Ή 2. Simple Example (Print Array)

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

int main() {
int a[] = {1, 2, 3, 4};
printArray(a, 4);
}


πŸ”Ή 3. Modify Array Inside a Function

void updateArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}

int main() {
int a[] = {1, 2, 3};
updateArray(a, 3);

for (int x : a)
cout << x << " ";
}

Output:

2 4 6

βœ” Original array is modified.


πŸ”Ή 4. Passing Array Using Pointer

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

βœ” Same behavior as arr[].


πŸ”Ή 5. Passing 2D Array to a Function

⚠️ Column size must be specified.

void printMatrix(int mat[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
}

int main() {
int matrix[2][3] = {{1,2,3},{4,5,6}};
printMatrix(matrix, 2);
}


πŸ”Ή 6. Passing Array with const (Read-Only)

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

βœ” Prevents accidental modification
βœ” Best practice for safety


πŸ”Ή 7. Array Size Is NOT Automatically Known

❌ This does NOT work:

void fun(int arr[]) {
int size = sizeof(arr); // wrong
}

βœ” Correct approach:

void fun(int arr[], int size) {
// use size
}

πŸ”Ή 8. Return Array from a Function (Using Dynamic Memory)

int* createArray() {
int *arr = new int[3]{1, 2, 3};
return arr;
}

int main() {
int *a = createArray();
delete[] a;
}

⚠️ Caller must free memory.


πŸ” Array vs Vector in Functions

Array Vector
Fixed size Dynamic size
Size passed manually v.size()
Less safe Safer

πŸ“Œ Summary

  • Arrays are passed by reference automatically

  • Function receives the base address

  • Size must be passed separately

  • Use const for read-only arrays

  • For dynamic needs, prefer vector

You may also like...