pointers in c
DESCRIPTION
A presentation describing about pointers in CTRANSCRIPT
EASTERN MEDITERRANEAN UNIVERSITY
EENG212 ALGORITHMS & DATA STRUCTURES
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
Pointer Variable Declarations and Initialization Pointer variables
Contain memory addresses as their values Normal variables contain a specific value (direct
reference)
Pointers contain address of a variable that has a specific value (indirect reference)
Indirection – referencing a pointer value
count
7
count7
countPtr
Pointer Variable Declarations and Initialization Pointer declarations
* used with pointer variablesint *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
y5
yptr
500000 600000
y
600000 5
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>45 int main()6 {7 int a; /* a is an integer */8 int *aPtr; /* aPtr is a pointer to an integer */910 a = 7;11 aPtr = &a; /* aPtr set to address of a */1213 printf( "The address of a is %p" 14 "\nThe value of aPtr is %p", &a, aPtr );1516 printf( "\n\nThe value of a is %d" 17 "\nThe value of *aPtr is %d", a, *aPtr );1819 printf( "\n\nShowing that * and & are inverses of "20 "each other.\n&*aPtr = %p" 21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );2223 return 0;24 }The address of a is 0012FF88The value of aPtr is 0012FF88 The value of a is 7The value of *aPtr is 7Proving that * and & are complements of each other.&*aPtr = 0012FF88*&aPtr = 0012FF88
The address of a is the value of aPtr.
The * operator returns an alias to what its operand points to. aPtr points to a, so *aPtr returns a.
Notice how * and & are inverses
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 functionvoid double( int *number ) {*number = 2 * ( *number );
} *number used as nickname for the variable
passed
1 /* Fig. 7.7: fig07_07.c
2 Cube a variable using call-by-reference
3 with a pointer argument */
4
5 #include <stdio.h>
6
7 void cubeByReference( int * ); /* prototype */
8
9 int main()
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;
18 }
19
20 void cubeByReference( int *nPtr )
21 {
22 *nPtr = *nPtr * *nPtr * *nPtr; /* cube number in main */
23 }
The original value of number is 5The new value of number is 125
Notice that the function prototype takes a pointer to an integer (int *).
Notice how the address of number is given - cubeByReference expects a pointer (an address of a variable).
Inside cubeByReference, *nPtr is used (*nPtr is number).
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
PsuedocodeInitialize array print data in original orderCall function bubblesort
print sorted arrayDefine 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 /* Fig. 7.15: fig07_15.c2 This program puts values into an array, sorts the values into3 ascending order, and prints the resulting array. */4 #include <stdio.h>5 #define SIZE 106 void bubbleSort( int *, const int );78 int main()9 {10 11 int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };12 int i;1314 printf( "Data items in original order\n" );1516 for ( i = 0; i < SIZE; i++ )17 printf( "%4d", a[ i ] );1819 bubbleSort( a, SIZE ); /* sort the array */20 printf( "\nData items in ascending order\n" );2122 for ( i = 0; i < SIZE; i++ )23 printf( "%4d", a[ i ] ); 2425 printf( "\n" );2627 return 0;28 }2930 void bubbleSort( int *array, const int size )31 {32 void swap( int *, int * );
Bubblesort gets passed the address of array elements (pointers). The name of an array is a pointer.
33 int pass, j;
34 for ( pass = 0; pass < size - 1; pass++ )
35
36 for ( j = 0; j < size - 1; j++ )
37
38 if ( array[ j ] > array[ j + 1 ] )
39 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 45 37Data items in ascending order 2 4 6 8 10 12 37 45
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
pointer variable vPtr
v[0] v[1] v[2] v[4]v[3]
3000 3004 3008 3012 3016location
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 notationb[ 0 ] = 10b[ 1 ] = 20b[ 2 ] = 30b[ 3 ] = 40
Pointer/offset notation wherethe pointer is the array name*( b + 0 ) = 10*( b + 1 ) = 20*( b + 2 ) = 30*( b + 3 ) = 40
Pointer subscript notationbPtr[ 0 ] = 10bPtr[ 1 ] = 20bPtr[ 2 ] = 30bPtr[ 3 ] = 40
Pointer/offset notation*( bPtr + 0 ) = 10*( bPtr + 1 ) = 20*( bPtr + 2 ) = 30*( bPtr + 3 ) = 40Press 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 10int 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”);elseprintf(“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;elselow = middle+1;}return -1;}
aptr[middle]