C++ Pointers Read Chapter 2 (P. 63 - 75). COP3530 – C++ Pointers Pointers Pointers provide a method of referencing the memory location of variables provide.

Slides:



Advertisements
Similar presentations
Chapter 6 Data Types
Advertisements

Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
A pointer is the memory address of a variable. A memory address is a physical location within a system’s memory space. A pointer variable is variable used.
DYNAMIC MEMORY MANAGEMENT. int x; When the source code containing this statement is compiled and linked, an executable file is generated. When the executable.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
@ Zhigang Zhu, CSC212 Data Structure - Section RS Lectures 6/7 Pointers and Dynamic Arrays Instructor: Zhigang Zhu Department of Computer Science.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
Dynamic Data Structures H&K Chapter 14 Instructor – Gokcen Cilingir Cpt S 121 (July 26, 2011) Washington State University.
Pointers1 Pointers & Dynamic Arrays Allocating memory at run-time.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 C++ Pointers Gordon College. 2 Regular variables Regular variables declared –Memory allocated for value of specified type –Variable name associated.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Data Structures.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
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.
Lecture 2 Arrays, Pointers, and Structures. Objective In this chapter, we will discuss several concepts: Arrays (first-class arrays, using vector) Strings.
1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
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.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Pointers Pointer a data type stores a memory address points to whatever the memory location contains A pointer is a variable that can store a memory address.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
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.
Edgardo Molina, CSC212 Data Structure - Section AB Lectures 6/7 Pointers and Dynamic Arrays Instructor: Edgardo Molina Department of Computer Science.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
1 Data Structures CSCI 132, Spring 2014 Lecture 10 Dynamic Memory and Pointers.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Dynamic memory allocation and Pointers Lecture 4.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
More C++ Features True object initialisation
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.
Review 1 List Data Structure List operations List Implementation Array Linked List.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic 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.
Pointers. The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte).
Data Structures in C++ Pointers & Dynamic Arrays Shinta P.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Pointers  * symbol and & symbol  Pointer operations  Pointer.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Arrays
Pointers and Dynamic Arrays
Data Structures and Abstract Data Types
Dynamically Allocated Memory
Pointers, Dynamic Data, and Reference Types
Dynamic Memory.
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

C++ Pointers Read Chapter 2 (P )

COP3530 – C++ Pointers Pointers Pointers provide a method of referencing the memory location of variables provide a method of referencing the memory location of variables analogy in real world: analogy in real world: ATM card has a number on it that references your bank account – ATM card has a number on it that references your bank account – ordinary variable declaration ordinary variable declaration int value; compiler allocates memory compiler also associates name with the memory address compiler puts the associated value in slots (if necessary) thus, & (address operator) can be used to retrieve the address (slot number) of the variable

Pointers (cont.) Declaring Pointers Declaring Pointers format: format: type * pointer; type * pointer; - this creates a variable named pointer that can be used to contain the address of another var of the defined type example: int * MyPointer; int * MyPointer; - creates a pointer called MyPointer that can be used to point to another int - the pointer is bound to the type that it is defined for - can also use typedef to create a pointer type typedef int * IntPointer; typedef int * IntPointer; IntPointer MyPointer; IntPointer MyPointer; (creates a pointer of the IntPointer type called MyPointer)

Pointers (cont.) Assigning values (addresses) to Pointers Assigning values (addresses) to Pointers format: format: int x = 4; int x = 4; MyPointer = &x; MyPointer = &x; indirection/dereferencing indirection/dereferencing again, MyPointer is a pointer that points to a memory address of some variable, in this case x. again, MyPointer is a pointer that points to a memory address of some variable, in this case x. MyPointer is basically an alias for the variable it points to MyPointer is basically an alias for the variable it points to if I wish to know what value is located at an address pointed to by a pointer, I put an * before the pointer – if I wish to know what value is located at an address pointed to by a pointer, I put an * before the pointer – * is called the indirection operator and using it like this is called dereferencing the pointer * is called the indirection operator and using it like this is called dereferencing the pointer

Pointers (cont.) ex: ex: typedef int * intPointer; void main() { int Value1 = 10; int Value1 = 10; int Value2 = 20; int Value2 = 20; intPointer Pointer1; intPointer Pointer1; Pointer1 = &Value1; Pointer1 = &Value1; cout << "Value1 " << Value1 << endl; cout << "Value1 " << Value1 << endl; cout << "Pointer1 " << *Pointer1 << endl; cout << "Pointer1 " << *Pointer1 << endl; Pointer1 = &Value2; Pointer1 = &Value2; cout << "Value2 " << *Pointer1; cout << "Value2 " << *Pointer1; } What is output? –

Pointers (cont.) In the above example, if I wished to change the value of Value2, I could do so in two ways: In the above example, if I wished to change the value of Value2, I could do so in two ways: (old way) Value2 = 30; (old way) Value2 = 30; Or, I could use the pointer to change the value: Or, I could use the pointer to change the value: *Pointer1 = 30; - will reset the value that Pointer1 points to to 30.

Pointers (cont.) - Pointers and Classes - Can use pointers to point to class objects: Clock * ClockPtr; Clock * ClockPtr; ClockPtr ClockPointer; ClockPtr ClockPointer; ClockPointer = &Clock1; ClockPointer = &Clock1; - then you can easily pass objects to functions (will discuss later) - To reference a member function of an object pointer: (*ClockPointer).theHour(); (*ClockPointer).theHour(); - or use the class pointer selector operator: - or use the class pointer selector operator: ClockPointer ->theHour(); - will execute theHour() function of the Clock1 object (pointed to by ClockPointer)

Pointers (cont.) Assign Pointer to a Pointer int x = 4, y = 5; IntPointer Pointer1 = &x; intPointer Pointer2 = &y; Pointer1 = Pointer2; - both pointers now point to address of variable y - thus the following statement: cout << *Pointer1 << " " << *Pointer2 << endl; Will produce the following output: 5 5 (since derferencing both will give the value contained in y) - this is often difficult to debug - (the aliasing problem)

Why Use Pointers? / Pointers with function arguments - original versions of C did not have & operator with functions - if needed to pass variables by reference, you had to pass the address of the variable: void Doubleit(int &n) { n *= 2; n *= 2;} call: DoubleIt(x); Can be written: void Doubleit(intPointer Iptr) { *Iptr *= 2; *Iptr *= 2;} call: DoubleIt(&x); call: DoubleIt(&x);

Pointers and Arrays Pointers and Arrays when assigning arrays to pointers, the pointer will point to the starting point of the array when assigning arrays to pointers, the pointer will point to the starting point of the array char MyArray[10]; typedef char * CharPointer; CharPointer myPtr; myPtr = MyArray; //will point to slot 0 of MyArray

Pointers (cont.) Other operations Other operations comparisons: comparisons: can use regular relational ops to see if two pointers point to same memory space: can use regular relational ops to see if two pointers point to same memory space: if (Pointer1 == Pointer2) //true if point to same address if (Pointer1 == Pointer2) //true if point to same address if (Pointer1 != Pointer2) // true if they point to different if (Pointer1 != Pointer2) // true if they point to different arithmetic: arithmetic: can add to/subtract from pointers: can add to/subtract from pointers: intPointer Pointer1; intPointer Pointer1; Pointer1++; Pointer1++; - will add the size of that pointer to the pointer (move to next slot in memory)

More Pointer Operations: int myInts[10]; IntPointer myPointer; myPointer = MyInts; //points to slot 0 for (int i = 0; i < 10; i++) { *myPointer = 0; *myPointer = 0; myPointer++; myPointer++;} - will initialize entire array to 0's

Dynamic Memory and Pointers - in all previous examples, memory is allocated for variables when program is compiled - programmer is forced to know the size of memory needed when the program is written; - not always efficient dynamic allocation: dynamic allocation: allowing the program to determine the size of memory needed at run-time allowing the program to determine the size of memory needed at run-time two steps: two steps: 1) acquire the memory when needed (allocate) 1) acquire the memory when needed (allocate) 2) discard the memory when done (deallocate) 2) discard the memory when done (deallocate)

Dynamic Memory (cont.) Acquiring memory with new operation - new: Acquiring memory with new operation - new: used to request additional memory when program is running used to request additional memory when program is running format: format: new VariableType; new VariableType; ex: ex: int * intPtr; int * intPtr; intPtr = new int; intPtr = new int; - requests a size in memory big enough to hold an int - if able, intPtr will be assigned the adress of the slot; - if unable, the null address (0) is assigned - If the null adress is not assigned intPtr is said to be an anonymous variable (has no name assigned to it) - Can access the variable by using dereferencing: cin >> *intPtr; *intPtr++; cin >> *intPtr; *intPtr++;

Dynamic Memory (cont.) To use new with an array: To use new with an array: new VariableType[ArraySize]; new VariableType[ArraySize];Ex: int TotalItems; cout << “Enter # of values to store:”; cin >> TotalItems; intPtr MyArray; MyArray = new int[TotalItems]; for (int i = 0; i < TotalItems; i++) { cout << “Enter Value: “; cout << “Enter Value: “; cin >> MyArray[i]; cin >> MyArray[i];}

Dynamic Memory (cont.) The Delete operator The Delete operator Used to remove data from the heap when no longer needed Used to remove data from the heap when no longer needed Heap also called runtime stack Heap also called runtime stack Delete: Delete: delete Pointer; delete Pointer; delete [] ArrayPointer; delete [] ArrayPointer;Ex: int * iptr; char * cptr; iptr = new int; cptr Memory; delete iptr; Memory = new char[100]; delete [ ] Memory; delete [ ] Memory;

Dynamic Memory- Deconstructors class Person { public: Person(); Person(); Person(char * N, int A); Person(char * N, int A); void Display(); void Display();private: char * Name; char * Name; int Age; int Age;};

Dynamic Memory – Deconstructors Person::Person(){ Name = 0; Age = 0; } Person::Person(char * N, int A) { int Len; Len = StrLen(N); Name = new char[Len + 1]; Strcpy(Name, N); Age = A; }

Dynamic Memory – Deconstructors Program allocates memory at runtime for each object declared: Program allocates memory at runtime for each object declared: Person P1(“Jim Jones”, 30); Person P2(“Steve Snapper”, 25); Make sure space is deallocated using deconstructor: Make sure space is deallocated using deconstructor:~Person();Person::~Person(){ delete [ ] Name; } Automatically removes object from heap when lifetime of that object is exhausted Automatically removes object from heap when lifetime of that object is exhausted

QUESTIONS? Prepare for TEST #1 Prepare for TEST #1 Chapter 1 of Book (Notes) Chapter 1 of Book (Notes) Review of Classes (Ch. 4 in Book and Notes) Review of Classes (Ch. 4 in Book and Notes) ADTs (Lists) (Ch. 6 in Book and Notes) ADTs (Lists) (Ch. 6 in Book and Notes) Pointers (Ch. 2 in Book and Notes) Pointers (Ch. 2 in Book and Notes) ONLINE HELP SESSION: ONLINE HELP SESSION: Tues. July 4 7:00 a.m. – 8:00 a.m. (tentatively) Tues. July 4 7:00 a.m. – 8:00 a.m. (tentatively) Log on to Yahoo! Instant Messenger (I will send you an INVITE to join a conference when I’m online) Log on to Yahoo! Instant Messenger (I will send you an INVITE to join a conference when I’m online)