Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.

Similar presentations


Presentation on theme: "Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer."— Presentation transcript:

1 Topic 5 Addresses, Pointers and Arrays

2 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer Arithmetic Array Names as Pointers Dynamic Memory Allocation Passing Arguments by Reference with Pointers Passing Arrays Returning Pointers from functions Pointers to structures

3 3 Pointers A pointer is a variable which contains an address as its value, e.g. int *p ; int x = 42; p= &x; Variable name AddressValue p2050020566 X 42

4 4 Pointer Variable Declarations and Initialization Can declare pointers to any data type dataType *pVarName; Pointer initialization  Initialized to 0, NULL, or address 0 or NULL points to nothing A pointer variable is declared with a type (e.g. int, double, etc) and must hold the address of a variable of the same type.  It is a syntax error if the type of the pointer does not match the type of the variable.  E.g. This is wrong: int *yptr; double y; yptr=&y; //error!!

5 5 Pointer Operators & (address operator)  Returns memory address of its operand  Example int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y  yPtr “points to” y yPtr y 5 yptr 5000060000 y 5 address of y is value of yptr

6 6 Pointer Operators * (indirection/dereferencing operator)  Returns synonym for object its pointer operand points to  *yPtr returns y (because yPtr points to y ). *yPtr is an alias for y. (i.e. it is another name for y )  Dereferencing a pointer means to obtain the contents (i.e. the value) to which the pointer is pointing to cout<<*yptr; //will print 5, based on previous slide *yptr = 9; // assigns 9 to y

7 7 Examples char ch1=‘A’; char ch2=‘Z’; char *p; p=&ch1; //p takes address of ch1 ch2 A Z 1402 ch1 1403 p 2403 1402

8 8 Examples *p=‘B’; //contents where p points to ch2 B Z 1402 ch1 1403 p 2403 1402

9 9 Examples p=&ch2; //p takes the address of ch2 ch2 B Z 1402 ch1 1403 p 2403 1403

10 10 Examples *p=‘Y’; ch2 B Y 1402 ch1 1403 p 2403 1403

11 11 Pointer Assignment int x=40,y=50; int *xptr, *yptr; //declare two pointers to int xptr=&x; yptr=&y; 40 50 x y xptr yptr

12 12 Pointer Assignment int x=40,y=50; int *xptr, *yptr; //declare two pointers to int xptr=&x; yptr=&y; yptr=xptr; 40 50 x y xptr yptr

13 13 Pointer Assignment int x=40,y=50; int *xptr, *yptr; //declare two pointers to int xptr=&x; yptr=&y; 40 50 x y xptr yptr

14 14 Pointer Assignment int x=40,y=50; int *xptr, *yptr; //declare two pointers to int xptr=&x; yptr=&y; *yptr=*xptr; 40 x y xptr yptr

15 15 Pointer Expressions and Pointer Arithmetic Pointer arithmetic  Increment/decrement pointer (++ or -- )  Add/subtract an integer to/from a pointer( + or +=, - or -= )  Pointer arithmetic meaningless unless performed on pointer to array 5 element char array  vPtr points to first element v[ 0 ], which is at location 3000 vPtr = 3000  vPtr++ ; sets vPtr to 3001 vPtr points to v[ 1 ]

16 16 Pointer Arithmetic Arithmetic expressions with pointers to character data Arithmetic expressions with pointers to integer data 1402 1406 P (P+1) 1402 1404 1403 P (P+1) (P+2)

17 17 Array Names as Pointers Arrays and pointers closely related When array created, compiler creates internal pointer constant for it  Stores array’s starting address  Name of array becomes name of pointer constant.  Therefore, array without a bracket and a subscript represents the starting address of the array An array name is a pointer constant  Stored address cannot be changed by an assignment statement

18 18 215837 int num[6]={2,1,5,8,3,7}; numnum+1num+2num+3num+4num+5 Array Names as Pointers (ctd’) num[0]num[1]num[2]num[3]num[4]num[5] 215837 *num*(num+1)*(num+2)*(num+3)*(num+4)*(num+5)

19 19 Example char str[4]=“Zen”; char *p; p=&str[0]; //or p=str; cout<<*p; //prints Z cout<<*(p+1); //prints e, i.e. the contents at the next memory location //pointed by p p++; //moves pointer to the next memory location cout<<*p; //prints e cout<<*p+1; //adds 1 to the contents of the memory location pointed to by p, //i.e. adds 1to ASCII of e, so it prints 102. Z n \0 e p

20 20 Another Example #include using namespace std; void main() { int grade[5]={2,1,5,8,3}; int *gPtr = grade; //assign pointer upon declaration. Same as // gPtr=grade; as separate statement following declaration int i; for (i=0; i<5; i++) cout<<*(grade+i)<<“ “<<grade[i]<<“ “<<*(gPtr+i) <<“ “<<gPtr[i]<<endl; } 2 2 1 1 5 5 8 8 3 3 Output: 5

21 21 Another Example (continued) Figure 14.11: The Variable Pointed to by *gPtr Is grade[0]

22 22 Another Example (continued) Offsets may be included in expressions using pointers  e.g., *(gPtr + 3) refers to variable three integers beyond variable pointed to by gPtr This is the variable grade[3] Subscripts automatically converted to equivalent pointer expression by compiler Parentheses in expression *(gPtr + 3) necessary to correctly access desired array element

23 23 Another Example (continued) Figure 14.12: An Offset of Three from the Address in gPtr

24 24 Another Example (continued) Table 14.1: Array Elements May Be Accessed in Two Ways

25 25 Example: Counting letters program using pointers #include //Counts the number of times the letter h appears in string using namespace std; void main() { int count=0; char word[20]; char *p; cout << "Type in a word: " ; cin >> word; p=&word[0]; //make p point to the memory location // of the first array element

26 26 Counting letters program using pointers while (*p!='\0') { if (*p=='h') count++; p++; //move to the next memory location } if (count==1) cout<<"The letter h appears 1 time"<<endl; else cout<<"The letter h appears " << count<<"times"<<endl; }

27 27 The new instruction Creating new variables at run time, e.g. int *Numbers ; int i = 0; Numbers = new int [10]; while(i<10) { cout << "Type in a number:" ; cin >> Numbers[i] ; i++; } Could combine the two statements into: int *Numbers=new int [10];

28 28 A program that uses dynamic storage #include using namespace std; void main() { int *Numbers ; int length ; int i ; cout<< "How many numbers do you need?"; cin >> length ; Numbers = new int [length] ; i=0 ; cout<<"Please enter "<<length<<" numbers:"<<endl; while(i<length) { cin >> Numbers[i] ; i++; }

29 29 The delete instruction When we no longer need storage space allocated by the new instruction, we can release it using the delete instruction. Suppose we have allocated storage space for a pointer to a single integer like this: int* p; p = new int ; When we no longer need the storage space taken up by the integer, we simply execute the instruction: delete p;

30 30 Using delete with arrays If we have allocated space for a whole sequence of integers, using a new instruction like this: int* p; p = new int[22]; then we should deallocate (release) the storage space using the delete instruction followed by empty array brackets. For example, to deallocate an array of elements pointed to by the pointer variable p, we would write: delete [] p;

31 31 Passing Arguments by Reference with Pointers There are three ways to pass arguments to a function in C++: 1) pass by value 2) pass by reference with reference arguments 3) pass by reference with pointers.

32 32 Passing Arguments by Reference with Pointers (ctd’) Pass-by-reference with pointer arguments  Pass address of argument using & operator  Arrays not passed with & because array name already pointer (see example function later)  * operator used as alias/nickname for variable inside of function

33 33 Example: swap() function with pointer parameters #include using namespace std; void swap(int *ptr1, int *ptr2) { int temp=*ptr1; *ptr1=*ptr2; *ptr2=temp; } void main() { int num1=30, num2=50; cout<<"Before swap: num1= "<<num1<<" and num2= "<<num2<<endl; swap(&num1, &num2); cout<<"After swap: num1= "<<num1<<" and num2= "<<num2<<endl; } Function swap() with two pointer to integer parameters Calling swap() passing the addresses of two integers

34 34 Program output: swap() function with pointer parameters Before swap: num1= 30 and num2= 50 After swap: num1= 50 and num2= 30

35 35 Passing Arrays When an array is passed to a function, its address is the only item passed  Address of first location used to store array  Arrays not passed with & because array name already pointer

36 36 Passing Arrays (ctd’) void fun(int list[], int size) An array parameter in a function can always be replaced by a pointer parameter void fun(char str[]) void fun(int *list, int size) void fun(char *str)

37 37 Example: Passing Arrays Could also be written as: int findMax(int *, int)

38 38 Example: Passing Arrays Or use: max=vals[0]; and retain subscript notation to refer to individual elements

39 39 Returning Pointers from Functions You can return a pointer from a function For example:  Write a function CopyArray() that takes as parameters an integer array and its size and returns a new array which is a copy of the array argument int* CopyArray(int *list, int size)

40 40 A Wrong Way to Return a Pointer //!!!!WRONG COPY FUNCTION!!!!!!! #include using namespace std; int* CopyArray(int *, int); int* CopyArray(int *list, int size) { int result[6],i; for (i=0;i<size; i++) { result[i]=list[i]; } return result; }

41 41 A Wrong Way to Return a Pointer void main() { int grade[6]={2,1,5,8,3,16}; int *p, i; p=CopyArray(grade, 6); for (i=0; i<6; i++) cout<<p[i]<<endl; } The output will be incorrect. The error is in the function definition. Because the array result is a local variable it does not exist when the function returns

42 42 The Correct Way to Return a Pointer //Corrected COPY FUNCTION!!!!!!! #include using namespace std; int* CopyArray(int *, int); int* CopyArray(int *list, int size) { int i; int *result=new int [size]; for (i=0;i<size; i++) { result[i]=list[i]; } return result; } Memory allocated with the new operator remains available until you explicitly free it or the program terminates. Main program is the same as in previous slide.

43 43 Pointers to Structures struct Temp{ int num1; int num2; }; Temp *ptr=new Temp; Data fields can be accessed in two ways:  (*ptr).num1 OR ptr->num1 num1 num2 ptr The contents where ptr points to, i.e. the structure, and then use the usual dot notation to access members

44 44 Example: Pointers to Structures #include using namespace std; struct Temp{ int num1; int num2; }; void main() { Temp *t1= new Temp; (*t1).num1=5; // or t1->num1=5; (*t1).num2=9; // or t1->num2=9; cout<<"Num1= "<<(*t1).num1<<" Num2= "<<(*t1).num2<<endl; // OR cout num1 num2<<endl; } num1 num2 t1 5 9 Num1= 5 Num2= 9 Output:

45 45 Arrays of Pointers Program 14.13: Pointer Array Example

46 46 Arrays of Pointers (continued) Figure 14.27: The Addresses Contained in the seasons[] Pointers


Download ppt "Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer."

Similar presentations


Ads by Google