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.

Slides:



Advertisements
Similar presentations
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Advertisements

Introduction to C Programming
Programming and Data Structure
Kernighan/Ritchie: Kelley/Pohl:
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Lecture 7 C Pointers Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays We’ve now looked at  Pointers  Arrays  Strings.
Chapter 8 Multidimensional Arrays C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
 2006 Pearson Education, Inc. All rights reserved Arrays.
POINTERS. 1.a) POINTER EXPRESSIONS Pointer variables can be used in expression If p1 and p2 are properly declared and initialized pointers then following.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
 2007 Pearson Education, Inc. All rights reserved C Pointers.
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Week 6: Functions - Part 2 BJ Furman 01OCT2012. The Plan for Today Comments on midterm exam (next week in lab!) Review of functions Scope of identifiers.
Lecture 12: Pointers B Burlingame 25 Nov Announcements Homework 6 due Homework 7 posted, due with the final  Final prep Take home Lab posted tonight.
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Lecture 13: Arrays, Pointers, Code examples B Burlingame 2 Dec 2015.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Computer And Programming Array and Pointer. Array provides a means to allocating and accessing memory. Pointers, on the other hand, provides a way to.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Arrays, Part 2 We have already learned how to work with arrays using subscript notation. Example: float myData[] = {3.5, 4.0, 9.34}; myData[0] += 2; printf("myData[0]
Arrays.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Lecture 6: More Decisions & Arrays B Burlingame 9 March 2016.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Lecture 11: Pointers B Burlingame 13 Apr Announcements Rest of semester  Homework Remaining homework can be done in pairs, turn in one paper with.
Lecture 7: Modular Programming (functions) B Burlingame 05 October, 2016.
Chapter 8 Arrays, Strings and Pointers
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Lecture 9: Pointers B Burlingame 25 October 2017.
INC 161 , CPE 100 Computer Programming
Hassan Khosravi / Geoffrey Tien
Lecture 6 C++ Programming
Lecture 10: Strings B Burlingame 4 April 2018.
Lecture 8b: Strings BJ Furman 15OCT2012.
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Lecture 18 Arrays and Pointer Arithmetic
MSIS 655 Advanced Business Applications Programming
Overloading functions
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Presentation transcript:

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  Bring: text, notes, HW, lab reports, calculator  Covers everything through pointers Lab project 7 after midterm

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

What is a Pointer? - 1 Variables in general  Variable declaration informs compiler of two things: 1. Name of the variable 2. 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) int var1 = 0; 10FE Var address 0 intvar1 Var valueVar typeVar name Symbol Table Memory (8-bit) Address x10FE 0x10FF Bit x1100 0x1101

Bit Memory (8-bit) Address x10FE 0x10FF What is a Pointer? - 2 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 short int i, j; i = 3; j = i; 1100 short intj 10FE Address short inti ValueTypeName Symbol Table

What is a Pointer? - 3 Pointer variable  A variable that contains an address Declaring a pointer variable  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" #include 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; } &num1 means: the address for the variable num1 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.

Accessing What a Pointer Points To The indirection operator * gets the value at the address stored in the pointer #include 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; }

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?)

ASCII Table

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)

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: #include 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]); 0x%p\n",&test[i]); } return 0; } Format (1D array)  type array_name [num_elements]; Ex. Array of 4 characters named, 'test'

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

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];  the first element is test [0]  the fourth element is test [3] #include 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]); 0x%p\n",&test[i]); } return 0; } 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

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_practice3.c Note addresses  Ex. array_practice4.c Read from the keyboard /* array_practice3.c */ #include 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]); 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 /* array_practice5.c */ #include 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; }  Declaration for 2D 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"

Arrays of Multiple Dimensions - 2 Arrays of more than one dimension, cont.  Declaration for 3D array: int Ary3[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 (called, ‘row-major’ order)  Ary3[0][0][0]  Ary3[0][0][1]  Ary3[0][0][2]  etc. to Ary3[n x -1][n y -1][n z -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"

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]

Array Names An array name by itself is interpreted as a constant pointer to the first element of the array.  &test[0] is equivalent to test A constant pointer to the first element of test  test[0] is equivalent to *test first element of test #include int main() { int i=0; char test[]={'M','E','3','0'} printf("test[%d]==%c",i,test[i]); 0x%p\t",&test[i]); printf("test[%d]==%c", i, *test); test); for(i=1; i<4; i++) { printf("test[%d]==%c",i,test[i]); 0x%p\n",&test[i]); } return 0; } array_practice9.c

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

Passing an Array to a Function 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 #include void PrintArray(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 */ void PrintArray(int num_elem, char array[]) { int i; for(i=0; i<num_elem; i++) { printf("test[%d]==%c",i,array[i]); 0x%p\n",&array[i]); }

Review

References Jensen, T. (2003). A Tutorial on Pointers and Arrays in C, available from: m.. Visited 02OCT m Parlante, N. (1999) Pointer Basics, [online]. Available from: Passing Arrays to Functions, [online]. Available from: six.co.uk/c/f3_passing_arrays_to_functions.asp. Visited 12MAR six.co.uk/c/f3_passing_arrays_to_functions.asp Visited 03OCT