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
or
π Both are equivalent.
πΉ 2. Simple Example (Print Array)
πΉ 3. Modify Array Inside a Function
Output:
β Original array is modified.
πΉ 4. Passing Array Using Pointer
β Same behavior as arr[].
πΉ 5. Passing 2D Array to a Function
β οΈ Column size must be specified.
πΉ 6. Passing Array with const (Read-Only)
β Prevents accidental modification
β Best practice for safety
πΉ 7. Array Size Is NOT Automatically Known
β This does NOT work:
β Correct approach:
πΉ 8. Return Array from a Function (Using Dynamic Memory)
β οΈ 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
constfor read-only arraysFor dynamic needs, prefer
vector
