Lecture 19: Arrays Introduction
Monday, April 09, 2012[Up] [Previous Lecture] [Next Lecture]
Reading Assigned: 8.1 - 8.2
Homework Due: None
Homework Assigned: Homework 09 - Assigned last class
Classwork Assigned: None
Topics Covered:
- Quiz 3 today - Topics
- Remind me to start quiz at 6:00
- Homework 9 questions?
- Arrays
- Arrays allow us to create a set of numbered variables
- Arrays are a fixed size set of a given variable
- To declare an array, you specify the type and variable name as normal, then add "[10]" after the variable name, where 10 is the number of array elements
- An example of declaring an array
int x[10];
- This example defines a set of 10 integers, the array is called "x"
- An array allocates a set of memory large enough to store the specified number of array elements
- So an array of 10 characters would allocate at least 10 bytes (10 * 1 byte per character)
- An array of 10 integers would allocate at least 40 bytes (10 * 4 bytes per integer)
- An array of zero length is not a compliation error, but is not normally useful since it allocates no actual memory
- To access an individual integer in the array, you specify the array name, then add "[0]" where the number specifies the index of the array element to access
- Note that the first array element is always numbered zero, NOT one
- An example of accessing an array
int x[10]; x[0] = 10; printf("Element zero is %d\n", x[0]);
- You can use an array element just as you would use any other variable
- Trying to access an array element after the last valid number is a runtime error and will corrupt memory