1 / 23

Lecture 7: Arrays

Lecture 7: Arrays. BJ Furman 06OCT2012. The Plan for Today. Announcements Review of variables and memory Arrays What is an array? How do you declare and initialize an array? How can you use an array? Array Examples Array Practice. Announcements. Midterm this week in lab

Download Presentation

Lecture 7: Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 7: Arrays BJ Furman 06OCT2012

  2. The Plan for Today • Announcements • Review of variables and memory • Arrays • What is an array? • How do you declare and initialize an array? • How can you use an array? • Array Examples • Array Practice

  3. Announcements • Midterm this week in lab • Bring: text, notes, HW, lab reports, calculator • Covers everything through pointers • Lab project 7 after midterm

  4. Learning Objectives • Explain what a pointer is (review) • Explain what an array is • Declare and initialize an array • Use an array in a program

  5. Memory (8-bit) Address 0x10FE 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0x10FF 0x1100 0x1101 Symbol Table Var name Var type Var address Var value var1 int 10FE 0 Bit 7 6 5 4 3 2 1 0 What is a Pointer? - 1 int var1 = 0; • Variables in general • Variable declaration informs compiler of two things: • Name of the variable • Data type of the variable • Actions caused: • Bytes allocated in memory • Symbol table with name, address, and value • Can think of a variable as having two "values" • Value of what is stored at the memory location (rvalue) • Value of the memory location (its address) (lvalue)

  6. Variables in general, cont. Assigning a value to a variable (i = 3;) Value is copied to the memory location at the address listed in the symbol table Using a variable in an expression (j = i;) Value of what is stored at the memory location is accessed What is a Pointer? - 2 Memory (8-bit) Address 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0x10FE 0x10FF Symbol Table Name Type Address Value i short int 10FE Bit 7 6 5 4 3 2 1 0 j short int 1100 short int i, j; i = 3; j = i;

  7. What is a Pointer? - 3 Pointer variable A variable thatcontains anaddress Declaring apointervariable type * varname int* ptr1; float *ptr2; char * ptr3; Read as: "ptr1 is a pointer to an integer" "ptr2 is a pointer to a float" "ptr3 is a pointer to a char" &num1 means:the address forthe variable num1 • #include <stdio.h> • int main() • { • int num1; • int *ptr1 = &num1, *ptr2; • num1 = 7; • printf("size of num1: %d\n",sizeof(num1)); • printf("value of num1: %d\n",num1); • printf("address of num1: %p\n",&num1); • printf("address in ptr1: %p\n",ptr1); • return 0; • } • What is the size of num1? • Is &num1 == ptr1? • What address is stored in ptr2? Always initialize pointers you declare! An uninitialized pointer is like a loaded gun pointed in a direction that you don’t know.

  8. Accessing What a Pointer Points To #include <stdio.h> int main() { int num1; int *ptr1 = &num1; num1 = 7; printf("value of num1: %d\n", num1); printf("value of num1: %d\n", *ptr1); return 0; } • The indirection operator * gets the value at the address stored in the pointer

  9. Pointer - Practice 1 • Declare: • x_ptr, a pointer to an integer • y_ptr, a pointer to a double • What do the following statements do? • char *my_ptr, my_char1 = 'c', my_char2; • my_ptr = &my_char1; • my_char2 = *my_ptr; What is in: • my_ptr (in declaration? in second line?) • my_char1 • my_char2 (in declaration? in last line?)

  10. ASCII Table

  11. Why Use Pointers? • Allows a function to modify variables in the calling function (without using global variables) • Return more than one value from a function call • Pass a pointer to a large data structure rather than copying the whole structure • Arrays (coming next)

  12. What is an Array? #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; } • 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) • typearray_name [num_elements]; • Ex. Array of 4 characters named, 'test'

  13. What is an array? - 2 int nums [10]; • 10 element array of integers Element no. 3 is accessed by: nums [2] because indexing begins at 0

  14. Accessing Array Elements #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; } • 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]; • the first element is test [0] • the fourth element is test [3] • Be careful! • The C compiler may not stop you from indexing beyond the boundary of your array. (What could happen?) What is test[4]? array_practice2.c

  15. Initializing Array Elements /* 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; } • 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_practice3.c • Note addresses • Ex. array_practice4.c • Read from the keyboard

  16. Arrays of Multiple Dimensions - 1 /* 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; } • Arrays can have more than one dimension • 2D matrices commonly used in linear algebra • Declaration for2D array: • 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"

  17. Arrays of Multiple Dimensions - 2 • Arrays of more than one dimension, cont. • Declaration for 3D array: • int Ary3[nx][ny][nz]; • Enclose each row of initializers in its own set of braces • Order of storage: far right subscript increments first (called, ‘row-major’ order) • Ary3[0][0][0] • Ary3[0][0][1] • Ary3[0][0][2] • etc. to Ary3[nx-1][ny-1][nz-1] • To find the element number for Ary3[x][y][z] declared to be of size [I] [J] [K]: • ex. If I=J=K=10, Ary3[2][0][7]--> 2(10*10)+0+7+1=208th • Ex. array_practice6.c • Initializes a 4x3x2 element array • Can think of array2 as a "4-element array of 3x2 element arrays"

  18. Arrays - Practice 1 • Declare: • an array of 100 characters named char100 • a 3x4 array of doubles named data1 • Given intmy_array1[2][3]={{0,1,2},{3,4,5}}; • Find • my_array1[1][2] • my_array1[0][0] • my_array1[0][3]

  19. Array Names #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; } • An array name by itself is interpreted as a constant pointer to the first element of the array. • &test[0] isequivalent to test • A constant pointer to the first element of test • test[0] is equivalent to *test • first element of test array_practice9.c

  20. Pointer Arithmetic • Pointer arithmetic • array[n] is equivalent to *(array + n) • Using just the name 'array' is equivalent to a constant 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

  21. Passing an Array to a Function #include <stdio.h> voidPrintArray(int elements, char array[]); int main() { /* initialize the array */ char test[]={'M','E','3','0'}; /* get the size of the array */ int num_elem=sizeof(test)/sizeof(char); /* pass array to function */ PrintArray(num_elem, test); return 0; } /* PrintArray() function definition */ voidPrintArray(int num_elem, char array[]) { int i; for(i=0; i<num_elem; i++) { printf("test[%d]==%c",i,array[i]); printf(" @ 0x%p\n",&array[i]); } } • Prototype and function header need: • data type • array name • [ ] • Function call with actual name of array • Note: in the function prototype and function header char *array would also work

  22. Review

  23. References Jensen, T. (2003). A Tutorial on Pointers and Arrays in C, available from: http://home.netcom.com/~tjensen/ptr/pointers.htm. .Visited 02OCT2009 Parlante, N. (1999) Pointer Basics, [online]. Available from: http://cslibrary.stanford.edu/106/ Passing Arrays to Functions, [online]. Available from: http://irc.essex.ac.uk/www.iota-six.co.uk/c/f3_passing_arrays_to_functions.asp. Visited 12MAR2010. http://www.asciitable.com/. Visited 03OCT2009.

More Related