1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.

Slides:



Advertisements
Similar presentations
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Advertisements

Dynamic Memory Allocation
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Arrays and pointers Lone Leth Thomsen. March 2006Basis-C-5/LL2 What is an array An array is a consecutive series of variables that share one variable.
Kernighan/Ritchie: Kelley/Pohl:
1 Review of Class on Oct Outline  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Arrays and Strings. 2 An array is a collection of variables of the same type that are referred to through a common name. It is a Data Structure which.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
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.
Pointers Applications
1 Review of Chapter 6: The Fundamental Data Types.
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.
C programming---Arrays scalar: capable of holding a single data item aggregate variables: capable of holding a collections of values. Two kinds of aggregates.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Lecture 13 Static vs Dynamic Memory Allocation
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
ECE Application Programming
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
CHAPTER 7: Arrays CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (Feb 2012)
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Arrays and Pointers.
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
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.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Arrays. Arrays are objects that help us organize large amounts of information.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
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.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
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.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Stack and Heap Memory Stack resident variables include:
Hassan Khosravi / Geoffrey Tien
Pointers.
Programming and Data Structures
C Programming Language
Dynamic Memory Allocation
CS111 Computer Programming
Lecture 18 Arrays and Pointer Arithmetic
Dynamic Memory Allocation
prepared by Senem Kumova Metin modified by İlker Korkmaz
Outline Defining and using Pointers Operations on pointers
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Arrays, Pointers, and Strings
Presentation transcript:

1 Chapter 9 Arrays and Pointers

2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

3 One-Dimensional Arrays  What is an array?  A sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.

4 One-Dimensional Arrays  Declaration of an array  Data_Type: the type of elements  Size: constant integral expression size of the array The number of elements of the array Example: int grade[100]; float f[10000]; Data_type array_name[size] #define NUM 100 #include int main(void){ int grade[NUM]; int i, avg, sum = 0; printf("Input scores:\n"); for (i=0; i<NUM; i++) scanf("%d", &grade[i]); for (i=0; i<NUM; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("Average=%d\n", avg); }

5 One-Dimensional Arrays  Access elements in an array  Use an index int grade[100]; ograde[index], where index is an integral expression  Elements are indexed from 0 to size-1  index must lie in the range 0 to size-1 #define NUM 100 #include int main(void){ int grade[NUM]; int i, avg, sum = 0; printf("Input scores:\n"); for (i=0; i<NUM; i++) scanf("%d", &grade[i]); for (i=0; i<NUM; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("Average=%d\n", avg); }

6 One-Dimensional Arrays #include int main(void){ int a[5]; int i; for( i=0; i<5; i++) a[i]=i; printf("%d %d \n", a[1]+a[2], a[1]-1); } % a.out 3 0 #include int main(void){ int a[5]; int i; a[5]=1; } What is the potential problem of this code? index must lie in the range 0 to size-1

7 One-Dimensional Arrays  Memory allocation of an array  the compiler assigns an appropriate amount of memory, starting from a base address.  The base address is represented by the array name.

8 One-Dimensional Arrays  Memory allocation of an array  Example: int grade[100]; If 4 bytes is used to represent an integer, What is the size of memory assigned to the array? 100 * 4= 400 bytes

9 One-Dimensional Arrays  Memory assignment of an array  Example: int grade[100]; 400 bytes is allocated to grade The base address is represented by the array name, that is, grade. base address

10 One-Dimensional Arrays  Initialization  Arrays can be initialized within a declaration An array initializer is a sequence of initializing values written as a brace-enclosed, comma- separated list.  Example: float x[4] = {-1.1, 0.2, 3.0, 4.4};

11 One-Dimensional Arrays  Initialization (cont’d)  When a list of initializers is shorter than the number of array elements to be initialized, the remaining elements are initialized to zero #define NUM 10 #include int main(void){ int grade[NUM] = {99,89,89}; printf("%d\n", grade[3]); } 0

12 One-Dimensional Arrays  Initialization (cont’d)  If an array is declared without a size and is initialized to a series of values, it is implicitly given the size of the number of initializers.  Example: int a[]={3,4,5,6}; What is the value of sizeof(a)? 4*4=16

13 One-dimensional arrays  Summary  An array is a sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.  Declaration of an array: Data_type array_name[size]  Access elements in an array: p[index] oElements are indexed from 0 oIndex should be in range [0, size-1]  Memory allocation: an appropriate amount of memory, starting from a base address, represented by the array name.  Initialization

14 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

15 The relationship between arrays and pointers An array name:  the base address of the array  the initial location in memory where the array is stored;  the address of the first element (index 0) of the array. Memory Base address: grade grade[0] grade[1] grade[2] grade[99]

16 The relationship between arrays and pointers  An array name is the base address of the array  the initial location in memory where the array is stored;  the address of the first element (index 0) of the array.  an address, or pointer value  Difference betw. an array name and a pointer  A pointer is a variable that takes addresses as values. The value of a pointer can be changed.  An array name is a particular fixed address that can be thought of as a constant pointer. The value of an array name cannot be changed.

17 Class on Nov 8

18 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

19 Pointer Arithmetic and Element Size  Pointer Arithmetic  If p is a pointer to a particular type, then the expression p+1 yields the machine address for the next variable of that type  Given an array int a[10], &(a[i]) is equivalent to a+i

20 Pointer Arithmetic and Element Size #define NUM 5 #include int main(void){ int *p, grade[NUM]={100,80,90,90,80}; int sum = 0; p = grade; printf("p : %u\n", p); printf("p+1 : %u\n", p+1); printf("p+2 : %u\n", p+2); printf("*(p+1): %d\n", *(p+1)); } % a.out p : p+1 : p+2 : *(p+1): 80 If p is a pointer to a particular type,  p+1 is the machine address for the next variable of that type

21 Pointer Arithmetic and Element Size  Pointer Arithmetic  p+i and ++p and p+=i are defined in a similar fashion If p is a pointer to a particular type,  p+1 is the correct machine address for storing or accessing the next variable of that type

22 Pointer Arithmetic and Element Size #define NUM 5 #include int main(void){ int *p, grade[NUM]={90,80,70,60,50}; int sum = 0; p = grade; printf("%d\n", *(p++)); printf("%d\n", *(++p)); printf("%d\n", *(p+=2)); } % a.out If p is a pointer to a particular type,  p+1 is the machine address for the next variable of that type

23 Pointer Arithmetic and Element Size  Programming Problem  int grades[5];  Write a for loop to access each element of this array using pointer arithmetic. int *p; /* expr1: p points to the first element */ /* condition: p points to an element in the array */ /* expr3: p points to the next element */ for( expr1; condition; expr3) { …… }

24 Pointer Arithmetic and Element Size #define NUM 5 #include int main(void){ int *p, grade[NUM]={100,100,100,100,100}; int sum = 0; for(p=grade; p <= grade+NUM-1; ++p) sum += *p; printf("sum = %d\n", sum); return 0; } % a.out sum = 500

25 Pointer Arithmetic and Element Size  Pointer Arithmetic  If p and q are both pointing to elements of an array, then what is the value of (p – q) the int value representing the number of array elements between p and q. If p is a pointer to a particular type,  p+1 is the correct machine address for storing or accessing the next variable of that type

26 Pointer Arithmetic and Element Size #include int main(void){ double a[2], *p, *q; p = &a[0]; q = p +1; printf("%d\n", q-p); printf("%d\n", (int)q-(int)p); return 0; } % a.out 1 8 Assume a double is stored in 8 bytes. The value printed by the last statement is system-dependent. On many system a double is stored in eight bytes.

27 Pointer Arithmetic and Element Size  Summary  If p is a pointer to a particular type, p+1: oyields the correct machine address for storing or accessing the next variable of that type p++, ++p, p+=i : odefined in a similar fashion. p – q: othe int value representing the number of array elements between p and q.

28 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

29 Passing Arrays to Functions  Programming Problem:  Write a function to increment each element of an array by one. How to pass the values of elements of an array to a function? How to modify the values of elements of the array in the function?

30 #include void inc(int a[], int n){ int i; for (i=0; i<n; ++i){ a[i]=a[i]+1; } int main(void){ int a[]= {7, 3, 6, 2}; int i; for(i=0;i<3;i++) printf("%4d", a[i]); printf("\n"); inc(a, 4); for(i=0;i<3;i++) printf("%4d", a[i]); printf("\n"); } Write a function to increment each element by one?  How to pass the values of elements of an array to a function?  How to modify the values of elements of the array in the function?

31 Passing Arrays to Functions  Passing Arrays to Functions  In function definition, a formal parameter that is declared as an array is actually a pointer.

32 #include void inc(int a[], int n){ int i; for (i=0; i<n; ++i){ a[i]=a[i]+1; } int main(void){ int a[]= {7, 3, 6, 2}; int i; for(i=0;i<3;i++) printf("%4d", a[i]); printf("\n"); inc(a, 4); for(i=0;i<3;i++) printf("%4d", a[i]); printf("\n"); }  a formal parameter: that is declared as an array is actually a pointer.  a is a pointer Write a function to increment each element by one?

33 Passing Arrays to Functions  Passing Arrays to Functions  a formal parameter that is declared as an array is actually a pointer.  When an array is being passed, its base address is passed call-by-value. The array elements themselves are not copied. By using the base address, we can access and update the elements in an array

34 #include void inc(int a[], int n){ int i; for (i=0; i<n; ++i){ a[i]=a[i]+1; } int main(void){ int a[]= {7, 3, 6, 2}; int i; for(i=0;i<3;i++) printf("%4d", a[i]); printf("\n"); inc(a, 4); for(i=0;i<3;i++) printf("%4d", a[i]); printf("\n"); } Memory a[0] a[3] a[2] a[1] inc: a inc: n a[i]: the ith element (indexed from 0) in the array with based address a

35 Passing Arrays to Functions  Summary  In function definition, a formal parameter that is declared as an array is actually a pointer.  When an array is being passed, its base address is passed call-by-value. The array elements themselves are not copied. By using the base address, we can access and update the elements in an array

36 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

37 One-dimensional arrays  Summary  An array is a sequence of data items that are of the same type, that can be indexed, and that are stored contiguously.  Declaration of an array: Data_type array_name[size]

38 One-dimensional arrays  Summary  Access elements in an array: p[index] oElements are indexed from 0 oIndex should be in range [0, size-1]  The compiler assigns an appropriate amount of memory, starting from a base address, represented by the array name.  Initialization

39 One-dimensional arrays  Summary  The Relationship between Arrays and Pointers The array name is the base address of the array Difference betw. an array name and a pointer oA pointer is a variable that takes addresses as values.  The value of a pointer can be changed. oAn array name is a particular fixed address that can be thought of as a constant pointer.  The value of an array name is decided by the system and cannot be changed.

40 One-dimensional arrays  Summary  Pointer Arithmetic and Element Size If p is a pointer to a particular type, p+1: oyields the machine address for the next variable of that type p++, ++p, p+=i : odefined in a similar fashion. p – q: othe int value representing the number of array elements between p and q.

41 One-dimensional arrays  Summary  Passing Arrays to Functions Function definition: a parameter that is declared as an array is actually a pointer. When an array is being passed, its base address is passed call-by-value. The array elements themselves are not copied. oBy using the base address, we can access and update the elements in an array

42 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

43 Two-Dimensional Array An array is a sequence of data items  that are of the same type,  that can be indexed, and  that are stored contiguously.  An array can be of any type.  Question: What is an array of arrays?  Two-Dimensional array

44 Two-Dimensional Array  Two-dimensional array:  Arrays of arrays,  Example: int a[3][4]; oA two-dimensional array of int variables oa[i][j]: the element in the ith row, jth column of the array (counting from 0). a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]

45 Two-Dimensional Array #include int main(void){ int a[3][4], i, j, sum =0; for (i=0; i<3; ++i) for (j=0; j<4; ++j) a[i][j]=i+j; for (i=0; i<3; ++i){ for (j=0; j<4; ++j) printf("a[%d][%d] = %d ", i, j, a[i][j]); printf("\n"); } return 0; } a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]

46 Two-Dimensional Array #include int main(void){ int a[3][4], i, j, sum =0; for (i=0; i<3; ++i) for (j=0; j<4; ++j) a[i][j]=i+j; for (i=0; i<3; ++i){ for (j=0; j<4; ++j) printf("a[%d][%d] = %d ", i, j, a[i][j]); printf("\n"); } return 0; } % a.out a[0][0] = 0 a[0][1] = 1 a[0][2] = 2 a[0][3] = 3 a[1][0] = 1 a[1][1] = 2 a[1][2] = 3 a[1][3] = 4 a[2][0] = 2 a[2][1] = 3 a[2][2] = 4 a[2][3] = 5

47 Two-Dimensional Array #include int main(void){ int a[3][2], i, j; for (i=0;i<3;i++) for (j=0;j<2;j++) a[i][j]=i*10+j; printf("%d\n", a[2][1]/2); printf("%d\n", a[1][1] * (a[0][0]+2)); printf("%d\n", a[3][1]/2); } % a.out

48 Two-Dimensional Array  Two dimensional array: array of arrays  DataType array_name[n1][n2]; array of n1 arrays each of these n1 arrays is an array of n2 values of DataType  Example: int a[3][4]; a is an array that has 3 arrays each of these 3 arrays is an array of 4 ints;

49 Two-Dimensional Array Example: int a[3][4]; a[i], i=0,1,2 : an array of 4 ints,  a[0]: the 0 th row array: a[0][0], a[0][1], a[0][2], a[0][3] a[0] is the base address of this array  a[1]: the 1 st row array: a[1][0], a[1][1], a[1][2], a[1][3] a[1] is the base address of this array  a[2]: the 2 nd row array: a[2][0], a[2][1], a[2][2], a[2][3] a[2] is the base address of this array a[2][3] a[2][2] a[2][1] a[2][0] a[1][3] a[1][2] a[1][1] a[1][0] a[0][3] a[0][2] a[0][1] a[0][0] Memory a[0] a[1] a[2]

50 Two-Dimensional Array #include int main(void){ int a[3][4], i, j, *p; for (i=0;i<3;i++) for (j=0;j<4;j++) a[i][j]=i*10+j; p=a[0]; for (j=0;j<4;j++){ printf("%2d ", p[j]); } % a.out a[2][3] a[2][2] a[2][1] a[2][0] a[1][3] a[1][2] a[1][1] a[1][0] a[0][3] a[0][2] a[0][1] a[0][0] Memory a[0] a[1] a[2]

51 Two-Dimensional Array  Access an element of a two-dimensional array  int a[3][4];  Expressions equivalent to a[i][j] *(a[i]+j) *(&a[0][0]+4*i+j)

52 Two-Dimensional Array  int a[3][4];  Expressions equivalent to a[i][j]  *(a[i]+j) a[i]: the pointer to an array of the ith row. (a[i]+j): the address of the jth element in the array of ith row.  the element at the ith row and jth column. a[2][3] a[2][2] a[2][1] a[2][0] a[1][3] a[1][2] a[1][1] a[1][0] a[0][3] a[0][2] a[0][1] a[0][0] Memory a[0] a[1] a[2]

53 Two-Dimensional Array  int a[3][4];  Expressions equivalent to a[i][j]  *(&a[0][0]+4*i+j) &a[0][0]: the pointer to the first element. 4*i+j: the number of elements between the first element and the element at the ith row and jth column.  the element at the ith row and jth column. a[2][3] a[2][2] a[2][1] a[2][0] a[1][3] a[1][2] a[1][1] a[1][0] a[0][3] a[0][2] a[0][1] a[0][0] Memory a[0] a[1] a[2]

54 Two-Dimensional Array  Two-dimensional array:  Arrays of arrays DataType array_name[n1][n2]; oarray of n1 arrays oeach of these n1 arrays is an array of n2 values of DataType Example: int a[3][4]; oa is an array that has 3 arrays oeach of these 3 arrays is an array of 4 ints;  a[0], a[1], a[2] are arrays of 4 ints.

55 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

56 Multidimensional Array  Example  int a[2][2][3]; 2*2*3=12 elements The compiler allocates space for 12 contiguous ints. The base address of the array is &a[0][0][0] a [1] [1] [2] a [1] [1] [1] a [1] [1] [0] a [1] [0] [2] a [1] [0] [1] a [1] [0] [0] a [0] [1] [2] a [0] [1] [1] a [0] [1] [0] a [0] [0] [2] a [0] [0] [1] a [0] [0] [0] base address

57 Multidimensional Array  Initialization of a multidimensional array  int a[2][2][3] = { {{1,1,0}, {2,0,0}}, {{3, 0, 0}, {4, 4, 0}} };  Wherever there is an insufficient number of initializers listed, the remaining elements are initialized to zero int a[][2][3] = {{{1,1}, {2}},{{3}, {4, 4}}};  Initialize all array elements to zero: int a[2][2][3]={0};

58 Multidimensional Array  Memory allocation  Starting at the base address of the array, all the array elements are stored contiguously in memory.  The base address of the array is &a[0][0][0]  Example  int a[2][2][3]; a[1][1][2] a[1][1][1] a[1][1][0] a[1][0][2] a[1][0][1] a[1][0][0] a[0][1][2] a[0][1][1] a[0][1][0] a[0][0][2] a[0][0][1] a[0][0][0]

59 Multidimensional Array  Question: Consider array int a[2][2][3]. Given int values i, j, and k, is &a[i][j][k] equivalent to &a[0][0][0] + i*2*3 + j*3 +k ? a [1] [1] [2] a [1] [1] [1] a [1] [1] [0] a [1] [0] [2] a [1] [0] [1] a [1] [0] [0] a [0] [1] [2] a [0] [1] [1] a [0] [1] [0] a [0] [0] [2] a [0] [0] [1] a [0] [0] [0] base address int a[2][2][3] The number between the element a[i][j][k] and a[0][0][0] is i*2*3 + j*3 + k

60 Multidimensional Array  In the header of the function definition, the followng parameter declarations are equivalent:  int a[][9][2] a is a pointer to an array of arrays the element of these arrays is of type int [9][2]  int a[7][9][2]  int (*a)[9][2]

61 Multidimensional Array  Summary:  Declaration: int a[2][3][4]  Initialization  Memory allocation Starting at the base address of the array, all the array elements are stored contiguously in memory.  Parameter Declaration: int a[][9][2] int a[7][9][2] int (*a)[9][2]

62 Outline  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation

63 Dynamic Memory Allocation #define NUM 100 #include int main(void){ int grade[NUM]; int i, avg, sum = 0; printf("Input scores:\n"); for (i=0; i<NUM; i++){ scanf("%d", &grade[i]); } for (i=0; i<NUM; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("Average=%d\n", avg); } Programming Problem: Calculate the average score.  This code works only when the number of students is 100.  How to modify the code so it works for any number of students? During execution, the user can specify the number of students.

64 Dynamic Memory Allocation #include int main(void){ int n, *grade, i, sum=0, avg; printf("Enter the number of students: "); scanf("%d", &n); grade = calloc(n, sizeof(int)); for(i=0; i<n; ++i) scanf("%d", &grade[i]); for(i=0; i<n; ++i) sum += grade[i]; free(grade); avg=sum/n; printf("Average = %d\n", avg); } Contiguous allocation: Return a pointer to enough space in memory to store n int variables Release the space

65 Dynamic Memory Allocation  Memory Allocation functions, stdlib.h  calloc() : contiguous allocation Prototypes: void *calloc(size_t, size_t); calloc( n, object_size) oreturns a pointer to enough space in memory to store n objects, each of object_size bytes; oif the system is unable to allocate the requested memory, the pointer value NULL is returned. Example: oint *a; a = calloc(5, sizeof(int)); ofloat *b; b = calloc(10, sizeof(float));

66 Dynamic Memory Allocation  Memory Allocation functions, stdlib.h  malloc(): memory allocation Prototypes: void *malloc(size_t); malloc(object_size) oreturns a pointer to object_size bytes of memory oif the system is unable to allocate the requested memory, the pointer value NULL is returned. Example: oint *a; a = malloc(100*sizeof(int));

67 Dynamic Memory Allocation  Memory Allocation functions, stdlib.h  Difference between calloc() and malloc() The storage set aside by calloc() is automatically initialized to zero The storage set aside by malloc() is not initialized and therefore starts with garbage values.

68 Dynamic Memory Allocation  Memory Allocation functions, stdlib.h  Space allocated by calloc() and malloc() remains in use for the duration of the program unless it is released by the programmer Not released on function exit  void free(void *prt); Release the space allocated by calloc() or malloc();

69 Dynamic Memory Allocation  Summary  calloc(n, object_size) returns a pointer to enough space in memory to store n objects, each of object_size bytes Null is returned if allocation fails  malloc(object_size) returns a pointer to of object_size bytes of memory Null is returned if allocation fails  void free(void *prt); release the space allocated by calloc() or malloc();

70 End of Chapter 9  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing Arrays to Functions  Two-Dimensional Arrays  Multidimensional Arrays  Dynamic Memory Allocation