1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
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.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
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 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Pointers Applications
Arrays, Strings, and Pointers CSE 2451 Rong Shi. Arrays Store many values of the same type in adjacent memory locations Declaration [ ] Examples: – int.
C Programming Lecture 14 Arrays. What is an Array? b An array is a sequence of data items that are: all of the same typeall of the same type –a sequence.
Chapter 8 Multidimensional Arrays C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Systems Programming Concepts
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
chap8 Chapter 8 Arrays (Hanly) chap8 2 Data Structure Simple data types use a simple memory to store a variable. Data Structure: a.
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
Chapter 8 Arrays and Strings
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Arrays- Part 2 Spring 2013Programming and Data Structure1.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
C Arrays Systems Programming. Systems Programming: Arrays 22 ArraysArrays  Arrays  Defining and Initializing Arrays  Array Example  Subscript Out-of-Range.
Arrays in C.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Chapter 8 Arrays Instructor: Yuksel & Demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.8-2 What is an Array? Scalar data types use.
CPS120: Introduction to Computer Science Lecture 15 Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
POINTERS.
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Arrays and Pointers.
UNIT 8 Pointers.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Chapter 12: Pointers and Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 9 Functions.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
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: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
C Programming Lecture 15 Two Dimensional Arrays. Two-Dimensional Arrays b The C language allows arrays of any type, including arrays of arrays. With two.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
C arrays (Reek, Ch. 8) CS 3090: Safety Critical Programming in C.
User-Written Functions
Lecture 7 Arrays 1. Concept of arrays Array and pointers
Hassan Khosravi / Geoffrey Tien
Hassan Khosravi / Geoffrey Tien
C Passing arrays to a Function
7 Arrays.
Lecture 18 Arrays and Pointer Arithmetic
Outline Defining and using Pointers Operations on pointers
7 Arrays.
Presentation transcript:

1 CS 201 Array Debzani Deb

2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o

3 Quick Review int * ptr1, * ptr2; int a[10]; ptr1 = &a[2]; ptr2 = a; // equivalent to ptr2 = &a[0]; An array variable is actually a pointer to the first element of the array. ptr2 points to the first element of the array and get others by offset. Referring a[i] is same as referring *(a+i). a a+1 a+2.. ? ? ? ? ? ? ? ? Memory Addresses

4 Array Elements as Function arguments If we want to print the ith element of the array x[i], then we can do the following: printf(”%d\n”, x[i]); scanf(”%d”, &x[i]); We can also pass array elements as arguments to functions that we write. For example: swap1(x[i], x[i+1]); swap2(&x[i], &x[i+1]);

5 Having arrays as function arguments Besides passing individual array elements to functions, we can write functions that take entire arrays as arguments. There are several ways of passing arrays to functions but in each case we only pass the address of the array. This is very similar to what we did during “passing variables by reference…” As we are not passing a copy of the array – any changes to the array made within the function will also effect the original array. When an array name with no subscript appears in the argument list of a function call, what is actually stored in the function’s corresponding parameter is the address of the array. Example, int a[10]; foo(a); foo(&a[0]); // same as above

6 Using arrays in formal parameter list void foo(int x[10]); // sized array Store the address of the corresponding array argument (a in previous slide) to variable x and remember it as an array of 10 elements. void foo(int x[]); // unsized array The length of the array is not specified. Since it is not a copy, the compiler does not need to allocate space for the array and therefore does not need to know the size of the array. With this, we can pass an array of any size to function foo. void foo(int *x); // array pointer Function foo can take any integer array as argument.

7 C code Example int main(void){ int a[5]={1,2,3,4,5}; int i; clear1(a,5); clear2(a,5); for(i=0; i<5; i=i+1) printf("%d ", a[i]); return 0; } void clear1(int x[], int size){ int i; for(i=0; i<size; i=i+1) x[i] = 0; } void clear2(int *x, int size){ int *p; for(p=x; p<(x+size); p=p+1) // for(p=&x[0]; p<&x[size]; p=p+1) *p = 0; }

8 Passing array as function parameter Array names are pointers. The name of an array contain the address of its initial element, a = &a[0]; Passing an array as function argument copies the value of the pointer to the formal array parameter and points to the same location. Where is the array actually located?  At the data area of the function that declared it.  For an array declared as formal parameter, space is allocated in the function data area only for the address of the initial array element of the array passed as actual argument.

9 Arrays as Input Arguments ANSI C provides a qualifier that we can include in the declaration of the array formal parameter in order to notify the C complier that the array is only an input to the function and that the function does not intend to modify the array. This qualifier allows the compiler to mark as an error any attempt to change an array element within the function. void foo(const int x[], int size) The const tells C not to allow any element of the array x to change in the function foo.

10 Figure 8.9 Function to Add Two Arrays

11 Figure 8.10 Function Data Areas for add_arrays(x, y, x_plus_y, 5);

12 Returning an Array from a function(1) Returning arrays should work too - right? int a[5]; a = foo(); ….. int* foo() { int c[5] = {1,2,3,4,5}; return c; } Wrong! In C, it is not legal for a function’s return type to be an array.

13 Returning an Array from a function(2) Type problem between int[] and int*  a is a constant pointer type, you can’t change it. Array c is stored in function foo’s stack frame.  Return just copies the pointer, not the array.  Memory where the array c resides may be overwritten once function foo finishes its execution. To do it properly  Pass an array as a function argument from your calling function and modify it inside the called function.

14 Partially Filled Arrays Frequently, a program will need to process many lists of similar data These list may not all be the same length In order to reuse an array for processing more than one data set, the programmer often declares an array large enough to hold the largest data set anticipated. This array can be used for processing shorter lists as well, provided that the program keeps track of how many array elements are actually in use. One way to do this is to have the original array size declared as the highest needed, and then store a sentinel value after the last value inputted.

15 Multidimensional Arrays A multidimensional array is an array with two or more dimensions. We will use two-dimensional arrays to represent tables of data, matrices, and other two-dimensional objects. Thus int x[3][3] would define a three by three matrix that holds integers. Initialization is bit different int x[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}}; Both indices starts at 0. Think of it as x[rows][cols]. x[0][0]=1x[0][1]=2x[0][2]=3 x[1][0]=4x[1][1]=5x[1][2]=6 x[2][0]=7x[2][1]=8x[2][2]=9 Row Col inside a row

16 Three Dimensional Array int enroll[100][5][4]; The first dimension stores the course number. 100 of 2D matrices put one under another. The second dimension stores campus id. 5 vectors, each 4- element long. The last dimension stores the year number.

17 2D array in address space(1) How to store a multi- dimensional array into a one- dimensional memory space. Row major ordering assigns successive elements, moving across the rows and then down the columns, to successive memory locations. Address of a[row][col] = Base_Address + (row * row_size + col) Base_Address is the address of the first element of the array (A[0][0] in this case). char *base = &A[0][0]; Referring A[i][j] is same as referring *(base+4*i+j);

18 2D array in address space(2) int a[2][3]; // 2 rows and 3 cols Alternative interpretation: Three 1D array of 4 integers. The base address of the array is &a[0][0]. The array name a by itself is equivalent to &a[0]. This time it is a pointer to an array of 3 elements. Different ways to access (i,j) th element: a[i][j] *(a[i] + j) *((*(a+i)) + j) *(&a[0][0] + 4*i + j) a[1][2] a[1][1] a[1][0] a[0][2] a[0][1] a[0][0] a a+1

19 Multi-dimensional Arrays. Declarationint a[N];int b[M][N];int c[L][M][N]; Array elementa[i]b[i][j]c[i][j][k] Pointer to elementab[i]c[i][j] Pointer to 1D array of N element bc[i] Pointer to 2D array of M*N element c

20 Passing Multidimensional array (1) a[7][9][2] = {0}; … sum(arr,7); … int sum(int a[][9][2], int asize){ int i, j, k, sum = 0 for( i = 0; i<asize; ++i) { for( j = 0; j<9; ++j) { for( k = 0; k<2; ++k) { sum += a[i][j][k]; return sum; } For a multidimensional array we must declare all but the first dimension. Only 7 can be omitted.

21 Passing Multidimensional array (1) For correct calculation of addresses, the array size must be specified for every dimension except the first one. Why? Address of a[row][col] = b_add + (row * row_size + col)

22 Sorting an Array – Selection Sort Similar to sorting cards.

23 Figure 8.16 Trace of Selection Sort

24

25 Common Programming Errors The most common error in using arrays is a subscript- range error. An out-of-range reference occurs when the subscript value is outside the range specified by the array declaration.  In some situations, no run-time error message will be produced – the program will simply produce incorrect results.  Other times, you may get a runtime error like “segmentation fault” or “bus error” Remember how to pass arrays to functions. Remember that the first index of the array is 0