Vous êtes sur la page 1sur 24

EENG212 ALGORITHMS

& DATA STRUCTURES

POINTERS

EASTERN MEDITERRANEAN UNIVERSITY

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

Pointer Variable Declarations and


Initialization
Pointer variables
Contain memory addresses as their values
Normal variables contain a specific value (direct
reference)
count
7

Pointers contain address of a variable that has a


specific value (indirect reference)
Indirection referencing a pointer value
countPtr

count
7

Pointer Variable Declarations and


Initialization
Pointer declarations
* used with pointer variables
int *myPtr;

Declares a pointer to an int (pointer of type


int *)
Multiple pointers require using a * before each
variable declaration

int *myPtr1, *myPtr2;

Can declare pointers to any data type


Initialize pointers to 0, NULL, or an address

0 or NULL points to nothing (NULL preferred)

Pointer Operators
& (address operator)

Returns address of operand


int y = 5;
int *yPtr;
yPtr = &y;
// yPtr gets address of y
yPtr points to y

yPtr

y
5

yptr
500000

600000

y
600000

Address of y
is value of
yptr

Pointer Operators
* (indirection/dereferencing operator)

Returns a synonym/alias of what its operand


points to
*yptr returns y (because yptr points to y)
* can be used for assignment

Returns alias to an object


*yptr = 7; // changes y to 7

Dereferenced pointer (operand of *) must be


an lvalue (no constants)

* and & are inverses

They cancel each other out

1 /* Fig. 7.4: fig07_04.c


2
Using the & and * operators */
3 #include <stdio.h>
4
5 int main()
The address of a is the value
6 {
7
int a;
/* a is an integer */
of aPtr.
8
int *aPtr;
/* aPtr is a pointer to an integer */
9
The * operator returns an
10
a = 7;
11
aPtr = &a;
/* aPtr set to address of a */
alias to what its operand
12
points to. aPtr points to a,
13
printf( "The address of a is %p"
so *aPtr returns a.
14
"\nThe value of aPtr is %p", &a, aPtr );
15
16
printf( "\n\nThe value of a is %d"
17
"\nThe value of *aPtr is %d", a, *aPtr );
18
19
printf( "\n\nShowing that * and & are inverses of "
Notice how * and
20
"each other.\n&*aPtr = %p"
& are inverses
21
"\n*&aPtr = %p\n", &*aPtr, *&aPtr );
22
23
return 0;
24 }
The address of a is 0012FF88
The value of aPtr is 0012FF88
The value of a is 7
The value of *aPtr is 7
Proving that * and & are complements of each other.
&*aPtr = 0012FF88
*&aPtr = 0012FF88

Calling Functions by Reference


Call by reference with pointer arguments
Pass address of argument using & operator
Allows you to change actual location in memory
Arrays are not passed with & because the array name
is already a pointer
* operator

Used as alias/nickname for variable inside of function


void double( int *number )
{
*number = 2 * ( *number );
}

*number used as nickname for the variable passed

/* Fig. 7.7: fig07_07.c

Notice that the


Cube a variable using call-by-reference

function prototype
takes a pointer to an integer (int *).

with a pointer argument */

4
5

#include <stdio.h>

6
7

void cubeByReference( int * );

8
9

int main()

/*

Notice how the address of


prototype
number */
is given cubeByReference expects a
pointer (an address of a variable).

10 {
11

int number = 5;

12
13

printf( "The original value of number is %d", number );

14

cubeByReference( &number );

15

printf( "\nThe new value of number is %d\n", number );

16
17

return 0;

Inside cubeByReference, *nPtr


is used (*nPtr is number).

18 }
19
20 void cubeByReference( int *nPtr )
21 {
22

*nPtr = *nPtr * *nPtr * *nPtr;

23 }
The original value of number is 5
The new value of number is 125

/* cube number in main */

Bubble Sort Using Call-by-reference


Implement bubblesort using pointers
Swap two elements
swap function must receive address (using &) of array
elements
Array elements have call-by-value default
Using pointers and the * operator, swap can switch
array elements
Psuedocode
Initialize array
print data in original order
Call function bubblesort
print sorted array
Define bubblesort

Bubble Sort Using Call-by-reference


sizeof

Returns size of operand in bytes


For arrays: size of 1 element * number of elements
if sizeof( int ) equals 4 bytes, then
int myArray[ 10 ];
printf( "%d", sizeof( myArray ) );

will print 40

sizeof can be used with


Variable names
Type name
Constant values

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

/* Fig. 7.15: fig07_15.c


This program puts values into an array, sorts the values into
ascending order, and prints the resulting array. */
#include <stdio.h>
#define SIZE 10
void bubbleSort( int *, const int );
int main()
{
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int i;
Bubblesort gets passed

address of array elements


(pointers). The name of an
array is a pointer.

printf( "Data items in original order\n" );


for ( i = 0; i < SIZE; i++ )
printf( "%4d", a[ i ] );

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

for ( pass = 0; pass < size - 1; pass++ )

35
36

for ( j = 0; j < size - 1; j++ )

37
38
39

if ( array[ j ] > array[ j + 1 ] )


swap( &array[ j ], &array[ j + 1 ] );

40 }
41
42 void swap( int *element1Ptr, int *element2Ptr )
43 {
44

int hold = *element1Ptr;

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

Pointer Expressions and Pointer


Arithmetic
Arithmetic operations can be performed on

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

Pointer Expressions and Pointer


Arithmetic
5 element int array on machine with 4 byte

ints

vPtr points to first element v[ 0 ]

at location 3000 (vPtr = 3000)

vPtr += 2; sets vPtr to 3008

vPtr points to v[ 2 ] (incremented by 2), but the


machine has 4 byte ints, so it points to address
3008 location
3000

3004

v[0]

pointer variable vPtr

v[1]

3008
v[2]

3012
v[3]

3016
v[4]

The Relationship Between Pointers


and Arrays
Arrays and pointers closely related
Array name like a constant pointer
Pointers can do array subscripting operations
Declare an array b[ 5 ] and a pointer bPtr

To set them equal to one another use:


bPtr = b;

The array name (b) is actually the address of first


element of the array b[ 5 ]
bPtr = &b[ 0 ]

Explicitly assigns bPtr to address of first element


of b

The Relationship Between Pointers


and Arrays

Element b[ 3 ]

Can be accessed by *( bPtr + 3 )


Where n is the offset. Called pointer/offset notation

Can be accessed by bptr[ 3 ]


Called pointer/subscript notation
bPtr[ 3 ] same as b[ 3 ]

Can be accessed by performing pointer


arithmetic on the array itself
*( b + 3 )

/* Fig. 7.20: fig07_20.cpp


Using subscripting and pointer notations with arrays */
#include <stdio.h>
int main()
{
int b[] = { 10, 20, 30, 40 }; /* initialize array b */
int *bPtr = b;
/* set bPtr to point to array b */
int i;
/* counter */
int offset;
/* counter */
/* output array b using array subscript notation */
printf( "Array b printed with:\nArray subscript notation\n" );
/* loop through array b */
for ( i = 0; i < 4; i++ ) {
printf( "b[ %d ] = %d\n", i, b[ i ] );
} /* end for */

/* output array b using array name and pointer/offset notation */


printf( "\nPointer/offset notation where\n"
"the pointer is the array name\n" );
/* loop through array b */
for ( offset = 0; offset < 4; offset++ ) {
printf( "*( b + %d ) = %d\n", offset, *( b + offset ) );
} /* end for */
/* output array b using bPtr and array subscript notation */
printf( "\nPointer subscript notation\n" );
/* loop through array b */
for ( i = 0; i < 4; i++ ) {
printf( "bPtr[ %d ] = %d\n", i, bPtr[ i ] );
} /* end for */
/* output array b using bPtr and pointer/offset notation */
printf( "\nPointer/offset notation\n" );
/* loop through array b */
for ( offset = 0; offset < 4; offset++ ) {
printf( "*( bPtr + %d ) = %d\n", offset, *( bPtr + offset ) );
} /* end for */
return 0; /* indicates successful termination */
} /* end main */

Array b printed with:


Array subscript notation
b[ 0 ] = 10
b[ 1 ] = 20
b[ 2 ] = 30
b[ 3 ] = 40
Pointer/offset notation where
the pointer is the array name
*( b + 0 ) = 10
*( b + 1 ) = 20
*( b + 2 ) = 30
*( b + 3 ) = 40
Pointer subscript notation
bPtr[ 0 ] = 10
bPtr[ 1 ] = 20
bPtr[ 2 ] = 30
bPtr[ 3 ] = 40
Pointer/offset notation
*( bPtr + 0 ) = 10
*( bPtr + 1 ) = 20
*( bPtr + 2 ) = 30
*( bPtr + 3 ) = 40
Press any key to continue

Binary Search
Binary Search: Given a sorted array Binary

Search algorithm can be used to perform fast


searching of a searchkey on the sorted array.
The following program uses pointer notation
to implement the binary search algorithm for
the search key entered by the user in the
following array:
(3, 5, 9, 11, 15, 17, 22, 25, 37, 68)

#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;
}

int BinarySearch (int *aptr, int skey)


{
int low=0,high=SIZE-1,middle;
while(low <= high){
middle= (low+high)/2;
if(skey == *(aptr+middle))
return middle;
else if(skey <*(aptr+middle))
high = middle-1;
else
low = middle+1;
}
return -1;
}

aptr[middle]

Vous aimerez peut-être aussi