Week 8: Arrays and File I/O BJ Furman 21OCT2009
The Plan for Today Arrays What is an array? How do you declare and initialize an array? How can you use an array? Array Examples Array Practice File I/O
Learning Objectives Explain what an array is Declare and initialize an array Use an array in a program How to open and close files for reading and writing
What is an Array? So far we've dealt with scalar variables contain just one value Arrays are collections of data of the same type that occupy contiguous memory locations Individual values in the collection are called elements of the array Need to declare before use: Format (1D array) type array_name [num_elements]; Ex. Array of 4 characters named, 'test' #include <stdio.h> int main() int i; char test[4]; test[0]='m'; test[1]='e'; test[2]='3'; test[3]='0'; for(i=0; i<4; i++) printf("test[%d]=%c",i,test[i]); printf(" @ 0x%p\n",&test[i]); return 0;
Accessing Array Elements Individual elements of an array are accessed by their index number ** Important Note** Array indexing starts at zero (take note of this, it is easy to forget!) char test[4]; Be careful! the first element is test[0] the fourth element is test[3] #include <stdio.h> int main() int i; char test[4]; test[0]='m'; test[1]='e'; test[2]='3'; test[3]='0'; for(i=0; i<4; i++) printf("test[%d]=%c",i,test[i]); printf(" @ 0x%p\n",&test[i]); return 0; The C compiler may not stop you from indexing beyond the boundary of your array. (What could happen?)
Initializing Array Elements Use braces to enclose the elements Separate elements by commas Can set number of elements in declaration: Explicit: int nums[5] Implicit: int imp[ ] = 1, 2; Read from the keyboard Ex. array_practice4.c /* array_practice3.c */ #include <stdio.h> int main() int i; int nums[5]=0,1,2,3,4; for(i=0; i<5; i++) printf("nums[%d]=%d",i,nums[i]); printf(" @ 0x%p\n",&nums[i]); return 0;
Arrays of Multiple Dimensions - 1 Arrays can have more than one dimension 2D matrices commonly used in linear algebra Declaration for 2D array: /* array_practice5.c */ #include <stdio.h> int main() int i,j; int my_array1[2][3]=0,1,2,3,4,5; for(i=0; i<2; i++) printf("\n"); for(j=0; j<3; j++) printf("%d ", array1[i][j]); return 0; int my_array1[number_of_rows][number_of_columns]; Enclose each row of initializers in its own set of braces Note method to print and access individual elements Can think of array1 as a "2-element array of 3 elements"
Arrays of Multiple Dimensions - 2 Arrays of more than one dimension, cont. Declaration for 3D array: int my_array2[n x ][n y ][n z ]; Enclose each row of initializers in its own set of braces Order of storage: far right subscript increments first my_array2[0][0][0] my_array2[0][0][1] my_array2[0][0][2] etc. to my_array2[n x -1][n y -1][n z -1] Find element number for my_array2[x][y][z]: x( JK) + y( K) + z + 1 Ex. array_practice6.c Initializes a 4x3x2 element array Can think of array2 as a "4-element array of a 3x2 element arrays"
Arrays - Practice 1 Declare: an array of 100 characters named char100 a 3x4 array of doubles named data1 Given int my_array1[2][3]=0,1,2,3,4,5; Find my_array1[1][2] my_array1[0][0] my_array1[0][3]
Notes on Arrays An array name that is not followed by a subscript is interpreted as a pointer to the first element of the array. &test[0] is equivalent to test pointer to first element of test test[0] is equivalent to *test first element of test #include <stdio.h> int main() int i=0; char test[]='m','e','3','0' printf("test[%d]==%c",i,test[i]); printf(" @ 0x%p\t",&test[i]); printf("test[%d]==%c", i, *test); printf(" @0x%p\n", test); for(i=1; i<4; i++) printf("test[%d]==%c",i,test[i]); printf(" @ 0x%p\n",&test[i]); return 0;
Notes on Arrays - 2 Pointer arithmetic array[n] is equivalent to *(array + n) Using just the name 'array' is equivalent to a pointer to the first element of array (i.e., base address) Dereferencing the expression, where an integer n is added to 'array', is equivalent to indexing the array to its element at subscript n array names cannot be changed, but pointer variables can be changed may not have: array_name = &var; the array name is a constant pointer and may not be changed
Array File I/O Arrays are often used with data consisting of many elements Too tedious to handle I/O by keyboard and monitor File I/O is used instead File I/O and array example
Opening a File Key concepts: Declare a pointer to FILE, e.g. FILE *fp; Use fopen function with path to the file and file mode as arguments fp = fopen( file_name.txt, r ); Some common modes (see reference below for others): r for reading from a file Returns NULL if the file does not exist w for writing to a file Creates the file if it does not exist, or wipes out contents of the file if it already exists a to append to a file Creates the file if it does not exist, or starts writing at the end of the file if it already exists Use the file pointer as an argument in functions like fscanf, fprintf, etc.) Good idea to test the file was opened without error Test the return value of fopen fopen will return NULL if there is an error opening the file Reference: http://www.cppreference.com/wiki/c/io/fopen
Closing a File Function header: int fclose(file *fp); Good idea to test the file was closed without error Test the return value of fclose fclose will return EOF if there is an error closing the file Make sure you close all files that you opened somewhere in your program Reference: http://www.cppreference.com/wiki/c/io/fclose
Review
References Jensen, T. (2003). A Tutorial on Pointers and Arrays in C, available from: http://home.netcom.com/~tjensen/ptr/point ers.htm.visited 02OCT2009. http://www.asciitable.com/. Visited 03OCT2009.