CSE 100 Lecture Notes - Lecture 34: Function Prototype, Array Data Structure
Chapter 8: 2-D Arrays
● 8.9 Arrays as Function Arguments
○ Passing a single array element to a function is no different than passing a regular
variable of that data type
○ The function does not need to know that the value it receives is coming from an
array
■ displayValue(score[i]); //call
■ void displayValue(int item) // header
■ { cout << item << endl;
■ }
○ Passing an Entire Array
■ To define a function that has an array parameter, use empty [ ] to indicate
the array in the prototype and header
■ To pass an array to a function, just use the array name
● // Function prototype
● void showScores(int [ ]);
● //Function header
● void showScores(int tests[ ])
● //Function call
● showScores(tests);
○ Passing an Entire Array continued
■ use the array name, without any brackets, as the argument
■ You can also pass the array size as a separate parameter so the function
nows how many elements to process
● showScores(tests, 5); //call
● void showScores(int[ ], int); //prototype
● void showScores(int A[ ],
● int size) // header
○ Using typedef with a Passed Array
■ You can use a typedef to simplify function prototype and header
■ //Make intArray an integer array of unspecified size
■ typedef int intArray[];
■ //Function prototype
■ void showScores(intArray, int);
■ //Function header
■ void showScores(intArray tests, int size)
○ Modifying Arrays in Functions
■ Array parameters in functions are similar to reference variables
■ Changes made to array passed to a function are made to the actual array
in the calling function
■ The programmer must be careful that an array is not inadvertently
changed by a function
Document Summary
Passing a single array element to a function is no different than passing a regular variable of that data type. The function does not need to know that the value it receives is coming from an array. To define a function that has an array parameter, use empty [ ] to indicate the array in the prototype and header. To pass an array to a function, just use the array name. Use the array name, without any brackets, as the argument. You can also pass the array size as a separate parameter so the function nows how many elements to process. You can use a typedef to simplify function prototype and header. // make intarray an integer array of unspecified size. Array parameters in functions are similar to reference variables. Changes made to array passed to a function are made to the actual array in the calling function.