View
231
Download
1
Tags:
Embed Size (px)
Citation preview
1
Chapter 9 Arrays and Pointers
2
Chapter 9 Arrays and Pointers
One-dimensional arrays The Relationship between Arrays and
Pointers Pointer Arithmetic and Element Size Passing Arrays to Functions
Two-Dimensional ArraysMultidimensional ArraysDynamic 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 expressionsize of the arrayThe number of elements of
the array
Example: int grade[100]; float f[10000];
Data_type array_name[size]
#define NUM 100#include <stdio.h>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];o grade[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 <stdio.h>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 <stdio.h>
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.out3 0
#include <stdio.h>
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 gradeThe 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 <stdio.h>
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]
o Elements are indexed from 0o Index 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 ArraysMultidimensional ArraysDynamic 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 ArraysMultidimensional ArraysDynamic 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 <stdio.h>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.outp : 4290705240p+1 : 4290705244p+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
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 <stdio.h>
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.out907050
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 <stdio.h>
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.outsum = 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 <stdio.h>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.out18
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:o yields the correct machine address for storing
or accessing the next variable of that type
p++, ++p, p+=i :o defined in a similar fashion.
p – q:o the 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 ArraysMultidimensional ArraysDynamic 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 <stdio.h>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 <stdio.h>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 <stdio.h>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: n4290705256
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
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 ArraysMultidimensional ArraysDynamic 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 arraysSummary
Access elements in an array: p[index]
o Elements are indexed from 0o Index 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 arraysSummary
The Relationship between Arrays and PointersThe array name is the base address of the array Difference betw. an array name and a pointer
o A pointer is a variable that takes addresses as values. The value of a pointer can be changed.
o An 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 arraysSummary
Pointer Arithmetic and Element Size If p is a pointer to a particular type,
p+1: o yields the machine address for the next variable
of that type
p++, ++p, p+=i : o defined in a similar fashion.
p – q: o the int value representing the number of array
elements between p and q.
41
One-dimensional arraysSummary
Passing Arrays to FunctionsFunction 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.
o By 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 ArraysMultidimensional ArraysDynamic 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];o A two-dimensional array of int variableso a[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 <stdio.h>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 <stdio.h>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.outa[0][0] = 0 a[0][1] = 1 a[0][2] = 2 a[0][3] = 3a[1][0] = 1 a[1][1] = 2 a[1][2] = 3 a[1][3] = 4a[2][0] = 2 a[2][1] = 3 a[2][2] = 4 a[2][3] = 5
47
Two-Dimensional Array
#include <stdio.h>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.out1022-2130880
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 0th 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 1st 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 2nd 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 <stdio.h>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
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]; o array of n1 arrays o each of these n1 arrays is an array of n2
values of DataType
Example: int a[3][4];o a is an array that has 3 arrays o each 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 ArraysMultidimensional ArraysDynamic Memory Allocation
56
Multidimensional Array
Example int a[2][2][3];
2*2*3=12 elementsThe 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 zeroint 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 ArrayQuestion: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 ArraysMultidimensional ArraysDynamic Memory Allocation
63
Dynamic Memory Allocation
#define NUM 100#include <stdio.h>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 <stdio.h>#include <stdlib.h>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)
o returns a pointer to enough space in memory to store n objects, each of object_size bytes;
o if the system is unable to allocate the requested memory, the pointer value NULL is returned.
Example:o int *a; a = calloc(5, sizeof(int));o float *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)
o returns a pointer to object_size bytes of memory
o if the system is unable to allocate the requested memory, the pointer value NULL is returned.
Example:o int *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 memoryNull 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 ArraysMultidimensional ArraysDynamic Memory Allocation