Lecture 07
Lecture 07
If either index < 0 or index > ARRAY_SIZE - 1, then we say that the index is out of bounds.
Unfortunately, in C++, there is no guard against out-of-bound indices. Thus, C++ does not check
whether the index value is within range—that is, between 0 and ARRAY_SIZE -1. If the index
goes out of bounds and the program tries to access the component specified by the index, then
whatever memory location is indicated by the index that location is accessed. This situation can
result in altering or accessing the data of a memory location that you never intended to modify or
access.
A loop such as the following can set the index out of bounds:
for (i = 0; i <= 10; i++)
list[i] = 0;
Here, we assume that list is an array of 10 components. When i becomes 10, the loop
test condition i <= 10 evaluates to true and the body of the loop executes, which results
in storing 0 in list[10]. Logically, list[10] does not exist.
On some new compilers, if an array index goes out of bounds in a program, it is possible that the program
terminates with an error message
Suppose that you want to copy the elements of myList into the corresponding elements of yourList. The following
statement is illegal:
yourList = myList; //illegal
In fact, this statement will generate a syntax error. C++ does not allow aggregate operations on
an array. An aggregate operation on an array is any operation that manipulates the entire array as
a single unit.
To copy one array into another array, you must copy it component-wise—that is, one
component at a time. This can be done using a loop, such as the following:
for (int index = 0; index < 5; index ++)
yourList[index] = myList[index];
Note: cin >> yourList; //illegal To read data into yourList, you must read one component at a time, using a loop
Similarly, determining whether two arrays have the same elements and printing the
contents of an array must be done component-wise. Note that the following statements
are illegal in the sense that they do not generate a syntax error; however, they do not
give
the desired results.
cout << yourList;
if (myList <= yourList)
.
Arrays as Parameters to Functions
Now that you have seen how to work with arrays, a question naturally arises: How are arrays passed as
parameters to functions?
By reference only: In C++, arrays are passed by reference only.
Because arrays are passed by reference only, you do not use the symbol & when declaring an array as a
formal parameter.
When declaring a one-dimensional array as a formal parameter, the size of the array is
usually omitted. If you specify the size of a one-dimensional array when it is declared as
a formal parameter, the size is ignored by the compiler.
Example : in this example we write a simple program to pass array as a parameter to function and print the array
using the function.