Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing."— Presentation transcript:

1 1 Chapter 9 Arrays and Pointers

2 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 17 Class on Nov 8

18 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 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 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 : 4290705240 p+1 : 4290705244 p+2 : 4290705248 *(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 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 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 90 70 50 If p is a pointer to a particular type,  p+1 is the machine address for the next variable of that type

23 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 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 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 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 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 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 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 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 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 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 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 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] 4290705256 inc: a inc: n 4290705256 4 7 3 6 2 a[i]: the ith element (indexed from 0) in the array with based address a. 8 4 7 3

35 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 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 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 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 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 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 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 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 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 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 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 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 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 10 22 -2130880

48 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 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 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 0 1 2 3 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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


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

Similar presentations


Ads by Google