Arrays on Functions 12

Introduction to Programming

Assignment Operator
• Assignment operator does not work on arrays as it is on variables.
… int a[] = {1,2}, b = {2,3,4}; b = a; …

• b and a now refer to the same array which was originally just a. • A change in either reflects to both.
Introduction to Programming

Passing Arrays to Functions
• A function that accepts an int array as parameter is declared as follows:
change_array(int formal[], int size);

• Note that change_array has no way of knowing formal's size (number of elements) just by the array itself. • Passing an array to the above function can be illustrated as follows:
int actual[2] = {1,2}; change_array(actual,2);
Introduction to Programming

Passing Arrays to Functions
• Arrays are passed to functions by reference i.e. using the assignment operator =. • Hence, any change in formal is also a change in actual.

Introduction to Programming

Copying Arrays
• Can be done by copying each element to the destination array using a loop. • A more efficient way is to use the function memcpy declared in string.h
int source[] = {1,2}, dest[4]; memcpy(dest, source, sizeof(int)*2);
Introduction to Programming

Returning Arrays

Forces us to learn pointers which deals with memory addresses. Let's not do that, yet. An array can directly be modified by a function when passed, so we can think of it as some kind of a “return” mechanism.

Introduction to Programming

Sign up to vote on this title
UsefulNot useful