CIS3355:
Business Data Structures |
Accessing Numeric Arrays through Pointers If we were to declare variables one at a time, searching for a particular element in RAM would be cumbersome. e.g.
declaring the square roots of the numbers 1 to 10 would be: float
sqrt1=1.000,sqrt2=1.414, sqrt3=1.732, sqrt4=2.000,
sqrt5=2.236, sqrt 6=2.449, sqrt7=2.646, sqrt8=2.828, sqrt9=3.000,
sqrt10=3.162 And
searching for element 2.236 would be:
If(sqrt1==2.236)then printf(“Stored in sqrt1\n”); Else if(sqrt2==2.236)then
printf(“Stored in sqrt2\n”); Else
if(sqrt3==2.236)then printf(“Stored in sqrt3\n”);
Else if(sqrt4==2.236)then printf(“Stored in sqrt4\n”); …..And
so on until a match is found.
So
we want to store the elements in an array and access them through the use of
pointers to make the searching simpler. We
use the following C code to do this: #include
<stdio.h> void
main() {float sqrt[10]={1.0,1.414,1.732,2.0,2.236,2.449,2.645,2.828, 3.0,3.162}; //requesting 40 contiguous bytes of storage starting at
15012 to 15015 (floats
require4 bytes
of storage) float
*sqrtptr; // sqrtptr=sqrt; //set base address of sqrt (which is
15012) equal to contents of
sqrtptr while
(sqrtptr<=&sqrt[9])
//do the loop as long as
the contents of location sqrtptr (which is 15012) is <= the address
location of subscript 9 which is 15048 {if (*sqrtptr==2.236)
printf(“%5.3f found at address%p\n”,*sqrtptr,sqrtptr); sqrtptr++;}} //increments the contents of sqrtptr by
4 DON'T forget that array
subscripts start at element 0. DO use arrays instead of
creating several variables that store the same thing. For example, if you want
to store total sales for each month of the year, create an array with 12
elements to hold sales rather than creating a sales variable for each month.
Q Why is it better to use an
array instead of individual variables? A With arrays, you can group
like values with a single name. In Listing 8.3, 1,000 values were stored.
Creating 1,000 variable names and initializing each to a random number would
have taken a tremendous amount of typing. By using an array, you made the task
easy Q What happens if I use a
subscript on an array that is larger than the number of elements in the
array?
A If you use a subscript that
is out of bounds with the array declaration, the program will probably compile
and even run. However, the results of such a mistake can be unpredictable. This
can be a difficult error to find once it starts causing problems, so make sure
you're careful when initializing and accessing array elements.
1. If an array is declared with 10 elements, what is the subscript of the first element? Ans: zero2.
What is the name of the array, and how many elements does it have? float expenses[12];
Ans: The array is named expenses, and it
contains 12 elements. |