Académique Documents
Professionnel Documents
Culture Documents
POINTERS
POINTERS
Outline
Introduction
Pointer Variable Declarations and Initialization
Pointer Operators
Calling Functions by Reference
Using the const Qualifier with Pointers
Bubble Sort Using Call by Reference
Pointer Expressions and Pointer Arithmetic
The Relationship between Pointers and Arrays
Arrays of Pointers
Pointers
Powerful, but difficult to master
Simulate call-by-reference
Close relationship with arrays and strings
count
7
Pointer Operators
& (address operator)
yPtr
y
5
yptr
500000
600000
y
600000
Address of y
is value of
yptr
Pointer Operators
* (indirection/dereferencing operator)
function prototype
takes a pointer to an integer (int *).
4
5
#include <stdio.h>
6
7
8
9
int main()
/*
10 {
11
int number = 5;
12
13
14
cubeByReference( &number );
15
16
17
return 0;
18 }
19
20 void cubeByReference( int *nPtr )
21 {
22
23 }
The original value of number is 5
The new value of number is 125
will print 40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
bubbleSort( a, SIZE );
/* sort the array */
printf( "\nData items in ascending order\n" );
for ( i = 0; i < SIZE; i++ )
printf( "%4d", a[ i ] );
printf( "\n" );
return 0;
}
void bubbleSort( int *array, const int size )
{
void swap( int *, int * );
the
33
int pass, j;
34
35
36
37
38
39
40 }
41
42 void swap( int *element1Ptr, int *element2Ptr )
43 {
44
45
*element1Ptr = *element2Ptr;
46
*element2Ptr = hold;
47 }
Data items in original order
2
6
4
8 10 12 89 68
Data items in ascending order
2
4
6
8 10 12 37 45
45
37
pointers
Increment/decrement pointer (++ or --)
Add an integer to a pointer( + or += , - or -=)
Pointers may be subtracted from each other
Operations meaningless unless performed on
an array
ints
3004
v[0]
v[1]
3008
v[2]
3012
v[3]
3016
v[4]
Element b[ 3 ]
Binary Search
Binary Search: Given a sorted array Binary
#include <stdio.h>
#define SIZE 10
int BinarySearch(int *, int);
int main()
{
int a[SIZE]= {3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, key, pos;
printf(Enter the Search Key\n);
scanf(%d,&key);
pos = BinarySearch(a, key);
if(pos == -1)
printf(The search key is not in the array\n);
else
printf(The search key %d is at location %d\n, key, pos);
return 0;
}
aptr[middle]