Passing an Array to a Function
Contents
Example Code
- Code for in-class discussion.
Review on Arrays
- What is an array?
- indexed, nonempty collection of data elements of the same type
- memory for data elements is allocated contiguously
- Syntax
- declaration
type name[number of elements];
- Example:
int arr[3];
can be used with arrays to indicate that array elements cannot be modified after initializationconst
AخAconst int arr[] = {0, 1, 2};
int val arr[0]; // OK
arr[0] = 3; // compile-time error
- initialization
type name[] = { val0, val1, ..., };
type name[] { val0, val1, ..., };
- if there are fewer initializers in a brace-enclosed list then the uninitialized elements are initialized to 0.
- E.g.,
int name[5] {3}; int x[] = {};
- subscripting (accessing elements)
- name[index]
- Example:
int x = arr[2];
- Elements of an array are accessed by computing an offset from the starting address.
- Each element in an array has an index, which is a non-negative integer (i.e., integers starting at zero). The index can be used to identify an element in the array.
- subscript operator - E1[E2] is identical to (*((E1)+(E2)))
- do not use an array index outside the bounds of the valid array indices
- declaration
- Comparing arrays to pointers
- an array is NOT a pointer
- a pointer variable holds a memory address, while an array holds one or more data elements
- the array variable cannot be modified; similar to a constant pointer
x
int arr[] {0, 1, 2};
int val = 3;
int* ptr = &val;
//arr = ptr; // error - array value cannot be modified
int* const ptr_test = &arr[0];
//ptr_test = ptr; // error - pointer value cannot be modified
*ptr_test = 3; // OK - value pointed to is NOT constant
- arrays can be initialized at their declaration, pointers cannot
- an array is NOT a pointer
- Consider the array
declared as:arr
int arr[3] {};
— the beginning memory address ofarr
arr
— value of the 0-index element inarr[0]
arr
— value of the 0-index element in*arr
arr
arr[0] == *arr
— memory address of the 0-index element in&arr[0]
arr
— memory address of the entire array; value of&arr
andarr
are the same, but their types are different&arr
Passing Arrays to Functions
- function declaration -
type name(type name[])
- E.g.,
print_array(int arr[])
- arr decays into a pointer, which does not include the array's size
- if an array is passed to a function, the function will have access to the contents of the original array
- put const in front of the array parameter to guarantee that the array contents will not be modified by the function