t13cpointersarithmetic.pps

11
Dale Roberts Department of Computer and Information Science, Department of Computer and Information Science, School of Science, IUPUI School of Science, IUPUI CSCI 230 Pointers Pointer Arithmetic Pointer Arithmetic Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]

Upload: anjali-naidu

Post on 12-Jul-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: t13CPointersArithmetic.pps

Dale Roberts

Department of Computer and Information Science,Department of Computer and Information Science,School of Science, IUPUISchool of Science, IUPUI

CSCI 230

Pointers

Pointer ArithmeticPointer ArithmeticDale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]

Page 2: t13CPointersArithmetic.pps

Dale Roberts

Pointer Expressions and Pointer ArithmeticPointer Expressions and Pointer Arithmetic

pv+n pv + n*sizeof(variable type that pointer point to)

Arithmetic operations can be performed on pointersArithmetic operations can be performed on pointersIncrement/decrement pointer (Increment/decrement pointer (++++ or or ----))ExampleExample: :

++vPtr, vPtr++,++vPtr, vPtr++,

--vPtr, vPtr----vPtr, vPtr--

Add an integer to a pointer( Add an integer to a pointer( ++ or or +=+= , , -- or or -=-=))

Pointers may be subtracted from each otherPointers may be subtracted from each other

Operations meaningless unless performed on an arrayOperations meaningless unless performed on an array

Page 3: t13CPointersArithmetic.pps

Dale Roberts

Example:

Five element Five element intint array on machine with 4 byte array on machine with 4 byte intintss

vPtrvPtr points to first element points to first element v[v[ 00 ]]whose address whose address location is location is 30003000 ( (vPtr = 3000vPtr = 3000))

vPtr += 2vPtr += 2;;

// // sets sets vPtrvPtr to to 30083008

vPtrvPtr points to points to v[v[ 22 ]] (incremented by 2), but (incremented by 2), but the machine has 4 byte the machine has 4 byte integersintegers, so it points to , so it points to address address 30083008

pointer variable vPtr

v[0] v[1] v[2] v[4]v[3]

3000 3004 3008 3012 3016location

Page 4: t13CPointersArithmetic.pps

Dale Roberts

Example: (double pointer)Assume long (long integer) is 4 bytes, and pointer variable is 2 bytes.long a[10]={5, 10, 15, …};long *pa, **ppa;int i=5;pa = &a;ppa = &pa;

Pointer Expressions and Pointer ArithmeticPointer Expressions and Pointer Arithmetic

Variable Address Value

a 640 5

644 10

648 15

… …

pa 700 640

ppa 800 700

Expression Value Note

pa+1 644 640+1*4

pa+3 652 640+3*4

pa+i 660 640+i*4

ppa+1 702 700+1*2

ppa+i 710 700+i*2

*pa+1 6 5+1

*(pa+1) 10 a[1]=pa[1]=*(a+1)

pa[2] 15 648

*ppa 640 value of pa

*ppa+1 644 pa+1

*(ppa+1) invalid *(702)

**ppa+1 6 a[0]+1 = 5+1

*(*ppa+1) 10 *(pa+1)=*(640+1*4)

ppa pa640700700800

a51015

640644648

652656660

Questions:

Page 5: t13CPointersArithmetic.pps

Dale Roberts

Pointer Expressions and Pointer ArithmeticPointer Expressions and Pointer Arithmetic

Subtracting pointersSubtracting pointersReturns number of elements from one to the other. IfReturns number of elements from one to the other. IfvPtr2 is a pointer pointing to v[vPtr2 is a pointer pointing to v[ 22 ];];

vPtr is a pointer pointing to v[vPtr is a pointer pointing to v[ 00 ];];

vPtr2 - vPtrvPtr2 - vPtr would produce 2 would produce 2

Pointer comparison ( Pointer comparison ( <<, , ==== , , >> ) )See which pointer points to the higher numbered array elementSee which pointer points to the higher numbered array element

Also, see if a pointer points to Also, see if a pointer points to 00

Pointers of the same type can be assigned to each otherPointers of the same type can be assigned to each otherIf not the same type, a cast operator must be usedIf not the same type, a cast operator must be used

Exception: pointer to Exception: pointer to voidvoid (type (type void *void *))Generic pointer, represents any typeGeneric pointer, represents any type

No casting needed to convert a pointer to No casting needed to convert a pointer to voidvoid pointer pointer

voidvoid pointers cannot be dereferenced pointers cannot be dereferenced

Page 6: t13CPointersArithmetic.pps

Dale Roberts

The Relationship Between Pointers and ArraysThe Relationship Between Pointers and Arrays

Arrays and pointers are closely relatedArrays and pointers are closely relatedArray name like a constant pointerArray name like a constant pointerPointers can do array subscripting operationsPointers can do array subscripting operations

Example: Declare an array Example: Declare an array b[b[ 55 ]] and a pointer and a pointer bPtrbPtr

bPtr = b;bPtr = b;// // To set them equal to one anotherTo set them equal to one another//// The array name (The array name (bb) is actually the address of first element of the array) is actually the address of first element of the array

bPtr = &b[bPtr = &b[ 00 ];];// // Explicitly assigns Explicitly assigns bPtrbPtr to address of first element of to address of first element of bb

To access element To access element b[b[ 33 ]:]: x=*(x=*( bPtrbPtr ++ 33 )) // // Where Where nn is the offset. Called pointer/offset notation is the offset. Called pointer/offset notation

x=bptr[x=bptr[ 33 ]] // // Called pointer/subscript notationCalled pointer/subscript notation

// bPtr[// bPtr[ 33 ]] same as same as b[b[ 33 ]]

x=*(x=*( bb ++ 33 )) // // Performing pointer arithmetic on the array itselfPerforming pointer arithmetic on the array itself

Page 7: t13CPointersArithmetic.pps

Dale Roberts

Pointers and ArraysPointers and Arrays

Strong relation between pointers and arraysStrong relation between pointers and arraysPointers and arrays can be used interchangeably.Pointers and arrays can be used interchangeably.The array name is equivalent to the address of the first The array name is equivalent to the address of the first element in the arrayelement in the array

ExampleExample::int a[10];int a[10];int *pa;int *pa;pa = &a[0]; /* is equivalent to pa = a */pa = &a[0]; /* is equivalent to pa = a */

So, So, a[1]a[1] *(pa+1) *(pa+1) pa[1] pa[1] *(a+1) *(a+1)&a[1]&a[1] pa+1 pa+1 a+1 a+1a[i]a[i] *(pa+i) *(pa+i) pa[i] pa[i] *(a+i) *(a+i)&a[i]&a[i] pa+i pa+i a+i a+ia[i]+=5a[i]+=5 *(pa+i)+=5 *(pa+i)+=5 pa[i]+=5 pa[i]+=5

ExampleExample::f(int f(int s[]s[])){ … { … }}

f(int *s){ … }

Page 8: t13CPointersArithmetic.pps

Dale Roberts

Arrays of PointersArrays of Pointers

Arrays can contain pointersArrays can contain pointersFor example: an array of stringsFor example: an array of strings

char *suit[4] = {"Hearts", "Diamonds", "Clubs", "Spades"};

Strings are pointers to the first characterStrings are pointers to the first character char *char * –– each element of each element of suitsuit is a pointer to a is a pointer to a charcharThe strings are not actually stored in the array The strings are not actually stored in the array suitsuit, only pointers to , only pointers to the strings are storedthe strings are stored

suitsuit array has a fixed size, but strings can be of any sizearray has a fixed size, but strings can be of any size

suit[3]

suit[2]

suit[1]

suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

Page 9: t13CPointersArithmetic.pps

Dale Roberts

Pointers to FunctionsPointers to Functions

Pointer to functionPointer to functionContains address of functionContains address of functionSimilar to how array name is address of first Similar to how array name is address of first elementelementFunction name is starting address of code Function name is starting address of code that defines functionthat defines function

Function pointers can beFunction pointers can be Passed to functionsPassed to functionsStored in arraysStored in arraysAssigned to other function pointersAssigned to other function pointers

Page 10: t13CPointersArithmetic.pps

Dale Roberts

void swap( int *element1Ptr, int *element2Ptr ) {int temp;temp = *element1Ptr;*element1Ptr = *element2Ptr;*element2Ptr = temp;}

int ascending( int a, int b ) {return b < a; /*swap if b is less than a*/}

int descending( int a, int b ) {return b > a; /*swap if b is greater than a*/}

Example: Bubble SortExample: Bubble Sort#define SIZE 10void bubble(int [],const int,

int (*)(int,int));int ascending( int, int );int descending( int, int );

int main() {int a[SIZE] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };bubble( a, SIZE, ascending );bubble( a, SIZE, descending );}

void bubble( int work[], const int size, int (*compare)(int,int)) {int pass, count;void swap( int *, int * );for (pass=1; pass<size; pass++) for (count=0; count<size-1; count++) if ((*compare)(work[count],work[count+1]))

swap(&work[count],&work[count + 1]);}

Page 11: t13CPointersArithmetic.pps

Dale Roberts

Function Function bubblebubble takes a function pointer takes a function pointer bubblebubble calls this helper function calls this helper functionthis determines ascending or descending sortingthis determines ascending or descending sorting

The argument in The argument in bubblesortbubblesort for the function for the function pointer:pointer:bool ( *compare )( int, int )bool ( *compare )( int, int )

tells bubblesort to expect a pointer to a function that tells bubblesort to expect a pointer to a function that takes two takes two intsints and returns a and returns a boolbool

If the parentheses were left out:If the parentheses were left out:bool *compare( int, int )bool *compare( int, int )

Declares a function that receives two integers and Declares a function that receives two integers and returns a pointer to a returns a pointer to a boolbool