Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.

Slides:



Advertisements
Similar presentations
Data Structures Using C++ 2E
Advertisements

Programming and Data Structure
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Informática II Prof. Dr. Gustavo Patiño MJ
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 10: Pointers by.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
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.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
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.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Chapter 9 Pointers Fall 2005 Csc 125 Introduction to C++
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 © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
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.
Pointers Pointers are a unique class of variables whose purpose is to “point” to other variables Pointers allow programmers direct access to memory addresses.
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.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
1 CS 132 Spring 2008 Chapter 3 Pointers and Array-Based Lists read p
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
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.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers Class #9 – Pointers Pointers Pointers are among C++ ’ s most powerful, yet most difficult concepts to master. We ’ ve seen how we can use references.
Pointers *, &, array similarities, functions, sizeof.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
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.
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
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.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
EGR 2261 Unit 11 Pointers and Dynamic Variables
Chapter 7 Pointers and C-Strings
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
Student Book An Introduction
Lecture 6 C++ Programming
DATA HANDLING.
Pointers and References
Chapter 9: Pointers.
Pointers, Dynamic Data, and Reference Types
Standard Version of Starting Out with C++, 4th Edition
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Pointers CS362

Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes simplifies code syntax) Reference dynamically allocated memory Read and write to binary files Create complex data structures (such as linked lists)

Pointers Pointers holds an address instead of a data value Used to access memory location where data resides We say that the pointer “points to” data Accessing memory via a pointer is called “indirect access” We’ve used pointers for some time (reference parameters)

Pointers To declare pointer variables use the “*” character It is used to both: Declare a pointer variable Access the values that the pointer variable points to In the end, a pointer (or pointer variable) points to (holds the address of) a variable of a specific data type. We will use the asterisk to define what type of data the pointer points to.

Pointers datatype* variableName; Asterisk indicates that the variable being declared is of type pointer-to-something It is read as “points to datatype” Asterisk can be at the end of datatype (as shown above), or at beginning of variable name: datatype *variableName; Either works, but be consistent.

Pointers Example: float* fptr; Declares a pointer called fptr that can hold the address where a float value exists in memory The pointer can only “point to” a float value (can’t point to any other data type)

Pointers Declared constants/variable have a unique starting address Address indicates the beginning of the memory area Addresses are assigned upon allocation The address operator “&” when followed by a variable name provides the address of a variable pointerVariableName = &dataVariableName;

Pointers Example: float num1, num2; float* fltPtr; num1 = 3.5; fltptr = &num1; fltptr points to the memory location assigned to num1. Pointers will always point to a specific type of memory (based upon the pointer type). Type of data stored must match the pointer data type.

Pointers You access the data value pointed to by a pointer using the de-referencing operator “*” (which is also the indirection operator) The asterisk followed by the pointer variable name access the value stored at the pointed-to address *ptrVariableName This reads “the value that prtVariableName points to”

Pointers Example: num2 = *fltPtr; (num 2 is assigned the value that fltPtr points to) num2 now has the value 3.5 stored at its memory location *fltPtr = 4.6; (where fltPtr points to (num1) is assigned the value 4.6) num1 now has the value 4.6 stored at its memory location

Pointers Pointers can be initialized when declared like any other variable: int sum; int *sPtr = ∑ Creates pointer sPtr and points it to the variable “sum” *sPtr = 5; Assign the value 5 to “where sPtr points to” (“sum”)

Pointers It is always a good idea to initialize pointers when declared If a pointer does not point to a valid location, it can be initialized with the null pointer value NULL means “points to nothing” float *myPtr = NULL; To use NULL the library must be included NOTE: Pointer variables can only store one of two values; an address or the value NULL

Pointers Same type pointers may be assigned each other values int main() { float num = 5.5; float *ftPtr1 = NULL; float *ftPtr2 = &num; *ftPtr2 = 4.4; ftPtr1 = ftPtr2; cout << fixed << showpoint << setprecision(1); cout << “Value is “ << *ftPtr1 << endl; return 0; }

Pointers Common Mistake 1: valid int *ptr1, *ptr2 (declares two pointers that point to integers) invalid int* ptr1, ptr2 (declares a pointer, and an integer variable) Common Mistake 2: given : int num; int *ptr; valid ptr = &num; invalid *ptr = &num; (ptr points to an integer location which cannot store the address of num) ptr = num;(ptr can only store an address or num, cannot accept an integer)

Pointers Pointers can point to any valid data type (including complex data types) For example pointer to an array: When using pointers with arrays the pointer will point to only one value within the array The array name is actually a “constant pointer” to the first value in the array (e.g. a pointer to the subscript 0 element in the array) Given: const int MAX = 50; int grades[MAX]; int* gradesPtr; gradePtr = grades; (gradePtr now points to the first element in the array) gradePtr = &grades[5]; (gradePtr now points to the 6 th element)

Pointers Warning: When using pointers to arrays it is the programmer’s responsibility to ensure that you do not attempt to point past the end of the array (similar to boundary test) Most C++ compilers will NOT identify an error in the code if you attempt to access past the end of the array, but the program will either crash or obtain strange or garbage values with the program runs

Pointers Some math and relational operators can be used with pointers For example, you can add units to a pointer A unit is one storage unit (e.g. size of int, float, char) Increments the address by size of data type This can be used to access arrays rather than using the normal array syntax

Pointers Array Syntax vs Pointer Syntax const int MAX = 10; int numbers[MAX]; int* arrayPtr = numbers; (arrayPtr points to top of array) accessing a cell using array syntax numbers[n] where “n” is a valid index value accessing a cell using pointer syntax *arrayPtr *(arrayPtr + n) where “n” does not exceed the array size

Pointers Array Syntax vs Pointer Syntax You can use either array or pointer syntax to initialize a pointer arrayPtr = &number[n] or arrayPtr = number + n; You can use either array or pointer syntax to access an array value arrayPtr[n] = nn; or *(arrayPtr + n) = nn; The following are equivalent: int arrayName[MAX]; int* arrayPtr = arrayName; arrayName == &arrayName[0] arrayName == arrayPtr arrayName + index == &arrayName[index] *(arrayPtr + index) == arrayName[index]

Pointers You may also use pointers to access records (struct) data To access the members of a structure use the de-referencing operator (asterisk) then select the member using the dot (.) operator Note: The de-referencing operation must be inside parenthesis due to low precedence of the de-referencing operator (the dot operator has a higher precedence)

Pointers Example: struct part { int partNum; string description; float price; bool inStock; }; part onePart; part* partPtr = &onePart; (*partPtr).price = 6.77; (result is assigned the value 6.77)

Pointers Using the parentheses, asterisk, and dot can be awkward Since using pointers and records are so common another operator was created to simplify access The member access operator was created: composed of the dash and greater-than operator (->) (no space) partPtr->price = 6.77;

Pointers The advantages of using a pointer become more obvious with an array of records const int MAX = 100; part inventory[MAX]; int num; part* partPtr = inventory; for (num = 0; num < MAX; num++) // This initializes all inStock members of all records { // in the inventory array to false; partPtr->inStock = false; // Note that the line partPtr++; moves the pointer partPtr++; // to the next record in the array (for each looping } // of the loop)