Array
Arrays
7.1
Arrays Hold Multiple Values
Copyright © 2009 Pearson Education, Inc. Publishing © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Copyright as PearsonAddison-Wesley
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Arrays Hold Multiple Values
• Array: variable that can store multiple values of the same type •Values are stored in adjacent memory locations • Declared using [] operator:
int tests[5];
Array - Memory Layout
• The definition:
int tests[5];
allocates the following memory:
first elementsecond element
third element
fourth element
fifth element
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-3
Copyright © 2009 Pearson Education, Inc.Publishing as Pearson Addison-Wesley
7-4
1
Array Terminology
In the definition int tests[5]; • int is the data type of the array elements • tests is the name of the array • 5, in [5], isthe size declarator. It shows the number of elements in the array. • The size of an array is (number of elements) * (size of each element)
Array Terminology
• The size of an array is:
– thetotal number of bytes allocated for it – (number of elements) * (number of bytes for each element)
• Examples:
int tests[5] is an array of 20 bytes, assuming 4 bytes for an int long doublemeasures[10]is an array of 80 bytes, assuming 8 bytes for a long double
7-5
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Copyright © 2009 Pearson Education, Inc.Publishing as Pearson Addison-Wesley
7-6
Size Declarators
• Named constants are commonly used as size declarators. const int SIZE = 5; int tests[SIZE]; • This eases program maintenance when the size ofthe array needs to be changed.
7.2
Accessing Array Elements
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
7-7
Copyright © 2009 Pearson Education, Inc....
Regístrate para leer el documento completo.