Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Programming and Data Structure
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Lecture 24: Strings. 2 Lecture Contents: t Library functions t Assignment and substrings t Concatenation t Comparison t Demo programs t Exercises.
1 Pointers Lecture Introduction Pointers  Powerful, but difficult to master  Simulate pass-by-reference  Close relationship with arrays and.
Kernighan/Ritchie: Kelley/Pohl:
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
ECE 353: Lab C Pointers and Structs. Basics A pointer holds an address to some variable Notation: – Dereferencing operator: * int *x is a declaration.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Programming Pointers. COMP104 Lecture 32 / Slide 2 Pointers l Pointers are objects whose values are the locations of other objects l Pointers are memory.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified by use by the MSU CMPS Dept. Chapter 10:
C++ Pointers Copies from SEE C++ programming course and from Starting Out with C++: Early Objects, 8/E by Tony Gaddis, Judy Walters and Godfrey Muganda.
Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction,
Pointers Chapter 9. Getting The Address Of A Variable Each variable in program is stored at a unique address Use address operator & to get address of.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
Pointers & Dynamic Data Structures Chapter Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes.
1 Pointers Arrays have a disadvantage: Their size must be known at compile time. We would like the capability to allocate an array-like object of any needed.
1 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Lecture 25: Practical Training on Pointers. 2 Lecture Contents: t Reminder on Arrays t Reminder on Strings t Reminder on Pointers t Demo programs, Exercises.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Engineering Computing I Chapter 5 Pointers and Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Slide 1 of 36. Attributes Associated with Every Variable Data type Data type Actual value stored in variable Actual value stored in variable Address of.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
3/16/2016Assoc. Prof. Stoyan Bonev1 COS240 O-O Languages AUBG, COS dept Lecture 01a Title: C++ as Conventional Prog Lan (Review) Reference: COS240 Syllabus.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers Lecture: 5. Topics 1 Pointers and the Address Operator 2 Pointer Variables 3 The Relationship Between Arrays and Pointers 4 Pointer Arithmetic.
Windows Programming Lecture 03. Pointers and Arrays.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Pointers.
Arrays and Pointers CSE 2031 Fall September 2018.
CSCE 210 Data Structures and Algorithms
Object Oriented Programming COP3330 / CGS5409
C++ Pointers and Strings
Chapter 9: Pointers and String
Chapter 9: Pointers and String
C++ Pointers and Strings
Presentation transcript:

Lecture 23: Pointers

2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs t Exercises

3 Pointer basics Pointers are variables that contain address values. Pointers are variables used to store address values. The basic concept of a pointer is: indirect access to data values

4 Pointer basics Given two integer variables alpha and beta. Variable alpha is defined, declared, initialized or assigned the value of 5. int alpha=5, beta; Problem: To copy the value of alpha(5) to beta Possible Solutions: t based on direct addressing t based on indirect addressing (pointers)

5 Pointer basics Direct access to data values: int alpha=5; int beta; beta = alpha;

6 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; ptr = α beta = *ptr;

7 Pointer basics Indirect access to data values: int alpha=5, beta, *ptr; // & - address of operator ptr = α //indirection or dereferencing operator beta = *ptr;

8 Declaration of pointers How to define (declare) pointers as variables? int *p1; p1 is a variable whose memory space will be used to store addresses of integer data.

9 Declaration of pointers How to define (declare) pointers as variables? char *p2; p2 is a variable whose memory space will be used to store addresses of character data.

10 Declaration of pointers How to define (declare) pointers as variables? double *p3; p3 is a variable whose memory space will be used to store addresses of double data.

11 How to use pointers? int alpha=5, *ptr; ptr = α // display alpha value/contents by direct/indirect addressing // C++ notation cout<< "\n" << alpha << " " << *ptr; // C notation printf(“\n%d %d”, alpha, *ptr);

12 How to use pointers? int alpha=5, *ptr=α // display address of alpha, I.e. contents of ptr // C++ notation cout << "\n " << &alpha << " " << ptr; // C notation printf(“\n%d %u %o %x %X %p”, ptr,ptr,ptr,ptr,ptr,ptr);

13 More on Pointers Pointers and Addresses

14 More on Pointers and Arrays t loop to traverse all array elements using direct access based on array subscripting expressions int a[10]; for (I=0;I<10;I++) { a[I]=I; cout << endl << a[I]; } t loop to traverse all array elements using indirect access based on pointers int a[10];int *pa;pa = &a[0]; for (I=0;I<10;I++) { *pa=I; cout << endl << *pa; pa++; }

15 More on Pointers and Arrays char amessage[] = “Now is the time!”; char *pmessage; pmessage = “Now is the time!”;

16 More on Pointers and Arrays char amessage[] = “Now is the time!”; int I=0; while(amessage[I] != ‘\0’) { cout << endl << amessage[I]; I++; }

17 More on Pointers and Arrays char *pmessage = “Now is the time!”; while(*pmessage != ‘\0’) { cout << *pmessage; pmessage++; } =================================================== char *pmessage = “Now is the time!”; char *q; q = pmessage + strlen(pmessage); while( pmessage < q ) { cout << *pmessage; pmessage++; }

18 More on Pointers Array of pointers char *pname[] = { “Illegal”, “Jan”, “Feb”,... “Nov”, “Dec” }; char aname[][15] ={ “Illegal”, “Jan”, “Feb”,... “Nov”, “Dec” };

19 More on Pointers Multidimensional arrays and pointers int a[10][20]; int *b[10];

20 Pointers and function arguments Problem: function to swap contents of two variables: void swap(int, int); swap(a, b); void swap(int p1, int p2) { int temp; temp=p1; p1=p2; p2=temp; }

21 Pointers and function arguments The solution: addresses specified as actual arguments void swap(int *, int *); swap(&a, &b); void swap(int *p1, int *p2) { int temp; temp=*p1; *p1=*p2; *p2=temp; }

22 More on Pointers Address arithmetic: char a[10]; a≡ a + 0≡&a[0] a + I≡&a[I] *(a+I)≡*&a[I]≡a[I]

23 More on Pointers Address arithmetic:int a[10], *p, *q; Assigning initial value to a pointer:p=q=a; Increment/decrement pointer: p++; p++; p--; Add a constant to pointer: q=q+8; Subtract constant from a pointer: q-=4; Comparison of two pointers:if(p p) Subtraction of two pointers: p=a; q=a+10; q-p is 10

24 More on Pointers Pointers to functions int fact(int n) { if(n==0) return 1; return n*fact(n-1); } int (*pf)(int);// pointer to function that has // one int param and returns int Direct function call Indirect function call cout << fact(5); pf = fact; cout << (*pf)(5);

25 More on Pointers Extract from Friedman/Koffman, chapter 13

Pointers & Dynamic Data Structures Chapter 13

27 Dynamic Data Structures t Arrays & structs are static (compile time) t Dynamic expand as program executes t Linked list is example of dynamic data structure Node Pointer Linked list

Pointers and the “new” Operator t Pointer Declarations –pointer variable of type “pointer to float” –can store the address of a float in p float*p; t The new operator creates a variable of type float and puts the address of the variable in pointer p p = new float; t Dynamic allocation - program execution

29 Pointers t Actual address has no meaning t Form:type*variable; t Example:float *p; ? P

30 new Operator t Actually allocates storage t Form:new type; new type [n]; t Example:new float;

31 Accessing Data with Pointers t * - indirection operator *p = 15.5; t Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p

32 Pointer Statements float*p; p = new float; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

33 Pointer Operations t Pointers can only contain addresses t So the following are errors: –p = 1000; –p = 15.5; t Assignment of pointers if q & p are the same pointer type –q = p; t Also relational operations == and !=

Manipulating the Heap t When new executes where is struct stored ? t Heap –C++ storage pool available to new operator t Effect of p = new node; t Figure 14.1 shows Heap before and after executing new operator

35 Effect on new on the Heap

36 Returning Cells to the Heap t Operation –delete p; t Returns cells back to heap for re-use t When finished with a pointer delete it t Watch dual assignments and initialization t Form:deletevariable; t Example:deletep;

37 Exercise Build programs based on pointers: t Exchange values of two integer variables (function swap); t Display a character string symbol by symbol on separate lines in forward and backward order; t Define the length of a character string (own version of strlen function); t Catenate two character strings (own version of strcat function); t Define a function returning the name of a month as a character string; t Operate as demo programs for pointers to functions.

38 Exercise Build programs based on pointers: t Display a character string symbol by symbol on separate lines in forward and backward order;

39 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { int I=0; cout << endl << str << endl; while (str[I] != ‘\0’) { cout << endl << str[I]; I++; }

40 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void main() { char *p = str; cout << endl << str << endl << p << endl; while ( *p != ‘\0’) { cout << endl << *p; p++; }

41 Exercise Build programs based on pointers: t Define the length of a character string (own version of strlen function);

42 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char m[]); void main() { cout << endl << strlenm(str) << endl; } int strlenm(char m[]) { int I=0, len; while (m[I] != 0x00) I++; len = I; return len; }

43 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; int strlenm(char *pm); void main() { char *p = str; cout << endl << strlenm(str) << “ “ << strlenm(p) << endl; } int strlenm(char *pm) { int len = 0; while (*pm != 0x00) { Ien++; pm++; ) return len; }

44 Exercise Build programs based on pointers: t Copy a character string (own version of strcpy function);

45 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char dst[], char src[]); void main() { char newstr[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char dst[], char src[]) { int I=0; while(( dst[I] = src[I] ) != ‘\0’)I++; }

46 Exercise 23.1 char str[] = “AUBG Blagoevgrad”; void copym(char *dst, char *src); void main() { char *newstr;newstr = new char[20]; copym(newstr, str); cout << endl << newstr << endl; } void copym(char *dst, char *src) { while(( *dst = *src ) != ‘\0’) { dst++; src++; } }

47 Before lecture end Lecture: Pointers More to read: Friedman/Koffman, Chapter 13

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Pointers and Dynamic Data Structures Problem Solving, Abstraction, and Design using C++ 5e by Frank L. Friedman and Elliot B. Koffman

49 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Data Structures Arrays & structs are static (compile time) Dynamic structures expand as program executes Linked list is example of dynamic data structure Node Pointer Linked list

50 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.1 Pointers and the new Operator Pointer Variable Declarations –pointer variable of type “pointer to float” –can store the address of a float in p float*p; The new operator creates (allocates memory for) a variable of type float & puts the address of the variable in pointer p p = new float; Dynamic allocation occurs during program execution

51 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers Actual address has no meaning for us Form:type*variable; Example:float *p; ? P

52 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley new Operator Actually allocates storage Form:new type; new type [n]; Example:new float;

53 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Accessing Data with Pointers indirection operator * *p = 15.5; Stores floating value 15.5 in memory location *p - the location pointed to by p 15.5 p

54 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Statements float *p; p = new float; *p = 15.5; cout << “The contents of the memory cell pointed to by p is “ << *p << endl; Output The contents of memory cell pointed to by p is 15.5

55 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Operations Pointers can only contain memory addresses So the following are errors: p = 1000; p = 15.5; Assignment of pointers is valid if q & p are the same pointer type q = p; Also relational operations == and !=

56 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Structs struct electric { string current; int volts; }; electric *p, *q; p and q are pointers to a struct of type electric

57 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p currentvolts p ??

58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Member Access through a Pointer p ->current = “AC”; p ->volts = 115; Could also be referenced as (*p).current = “AC”; (*p).volts = 115; currentvolts p AC115

59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Member Access through a Pointer Form:p ->m Example:p ->volts cout current volts << endl; Output AC115

60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers and Structs q = new electric; Allocates storage for struct of type electric and places address into pointer q Copy contents of p struct to q struct *q = *p; currentvolts p AC115 currentvolts q AC115

61 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers and Structs q ->volts = 220; q = p; currentvolts AC220 q AC 115 AC220 pq->currentq->volts p->currentp->volts q

62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13.2 Manipulating the Heap When new executes where is struct stored ? Heap –C++ storage pool available to new operator Effect of p = new electric;

63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Figure 13.1 Heap before and after execution of p - new node;

64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning Cells to the Heap Operation delete p; Returns cells back to heap for re-use When finished with a pointer, delete it Watch –multiple pointers pointing to same address –only pointers created with new are deleted Form:delete variable; Example:delete p;

65 Thank You For Your Attention