notes112

# notes112 - CS 251 Notes by Sean Catlin Notes for The Week...

This preview shows pages 1–4. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CS 251 Notes by Sean Catlin Notes for The Week of February 18-----February, 18----- Pointer Arithmetic The "+" and the "-" operators in points always scale the pointer to the type of object that the pointer points to. EX: char c[20]; char *pc; pc = &c[0]; Printing A Pointer EX: The code printf("pc = 0x%\x\n", pc); prints "pc = 0x2000" Printing Char Pointed To By p EX: *PC = 'A'; //(or *pc = 65;) 65 is the ASCII value of 'A' printf("*pc=%c\n" *pc); Printing The Pointer And What It Is Pointing To EX: The Code int ai[20]; int *pi; pi = ai[0]; //stored at address 0x4000 *pi = 5; printf("pi=0x%\x\n", pc); printf("*pi = %d \n", *pi); prints "pi=0x4000" "*pi=5" Addresses Of Pointers pi = pi+5; pi is at the address 0x3000 pi is pointing to the address 0x4014 it is pointing to 0x4014 because it started at 0x4000 and was incremented when 5 was added to pi. the equation for this is--- 0x4000 + (5 * sizeOf(int)) 0x4000 + (5 * 4) 0x4000 + (20) 0x4000 + 0x14 0x4014--- Pointer Identities EX: int a[20]; the next 4 statements are all equivalent to each other a[i] *(a+i) *(&a[0] + i) *(int)((char*)&a[0]+i*sizeOf(int)) myStrCpy EX: myStrCpy(char *dst, char *src) { //copies from src to dst //in C a string is an array of chars terminated by 0 // ex: src ---> h e l l o 0 //returns dst char *p = dst; while(*src != 0) { *p=*src; p++; src++; } *p=0; return dst; } Adding An Array Of Integers Using Pointers EX: int sumArray(int *a, int nElems) { int *pi=a; int *piEnd = a + nElems; int sum = 0; while(pi<piEnd) { sum = sum + *pi; pi++; } return sum; } a[i] expands to *(int)(char*)a+i*sizeOf(int) mySwap EX: void mySwap(viod *a, void *b, int elemSize) { //swaps the contents of two areas of memory // 'a' and 'b' byte by byte...
View Full Document

## This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue.

### Page1 / 11

notes112 - CS 251 Notes by Sean Catlin Notes for The Week...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online