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.

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Chapter 9 Pointers and Creating Data Structures.
Advertisements

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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
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.
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.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
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.
C++ for Engineers and Scientists Third Edition
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.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Copyright 2001 Oxford Consulting, Ltd1 January Pointers and More Pointers Pointers and Arrays We’ve now looked at  Pointers  Arrays  Strings.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
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.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
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.
CS-1030 Dr. Mark L. Hornick 1 Pointers are fun!
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 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.
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.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Lecture 7 Pointers & Refrence 1. Background 1.1 Variables and Memory  When you declare a variable, the computer associates the variable name with a particular.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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).
1  Lecture 12 – Pointer FTMK, UTeM – Sem /2014.
CS162 - Topic #12 Lecture: –Arrays with Structured Elements defining and using arrays of arrays remember pointer arithmetic Programming Project –Any questions?
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Lecture.
Pointers. Introduction to pointers Pointer variables contain memory addresses as their values. Usually, a variable directly contains a specific value.
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.
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.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Pointers What is the data type of pointer variables?
Standard Version of Starting Out with C++, 4th Edition
Chapter 9: Pointers.
Student Book An Introduction
Values – also known as scalars (eg. int, double, char, float)
Pointers and References
Chapter 9: Pointers.
Pointers, Dynamic Data, and Reference Types
MSIS 655 Advanced Business Applications Programming
7 Arrays.
POINTER CONCEPT 4/15/2019.
Data Structures and Algorithms Introduction to Pointers
Standard Version of Starting Out with C++, 4th Edition
Pointers and References
POINTER CONCEPT 8/3/2019.
Presentation transcript:

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.

Address of variable Each variable occupies some bytes in memory (according to its size) Each byte of memory has a unique address so that it can be accessed (just like the address of our homes) Variable names are actually titles given to these addresses Such as the ‘white house’ When we use a variable, the compiler fetches the value placed at its address or writes a new value to that address

Address of variable How can we find the address of that variable? The “&” (Ampersand) operator returns the address of a variable cout << a << endl; cout << &a << endl;

Pointers Pointers are just variables storing numbers –but those numbers are memory addresses A pointer that stores the address of some variable x is said to point to x. A pointer is declared by putting a star (or '*') before the variable name. To access the value of x, we’d need to dereference the pointer.

Motivation for using Pointers To return more than one value from a function. To pass arrays and strings more conveniently from one function to another. To manipulate arrays more easily by moving pointers to them. Obtaining memory from the system In more advanced programming, such as To create complex data structures, such as linked lists and binary trees For dynamic memory allocation and de-allocation

Pointers Declaration of pointer to an int int* intPtr; Initializing a pointer int val = 42; int* intPtr = &val; The ampersand (or '&') before val means "take the address of val". The pointer intPtr is assigned the address of val, which is another way of saying that intPtr now points to val.

Pointers 0028F C7 Pointing to val F868 val intPtr

Pointers If we print out the value of intPtr, we'll get the address of val. To get the data that intPtr actually points at, we have to dereference intPtr with the unary star operator ‘*’ int val = 42; int *intPtr = &val; cout << "&val: " << &val << endl;//address of val cout << "intPtr: " << intPtr << endl; //..again, address cout << "*intPtr: " << *intPtr << endl; // displays 42 Note that the star (or '*') operator has many uses. When used in a binary context, it can mean multiplication. When used in a variable declaration, it means "this variable is a pointer". When used in an expression as a single-argument operator, it can mean "dereference". With so many uses, it's easy to get confused.

Pointers Since intPtr points to val, any changes that we make to val will also show up when we dereference intPtr: int val = 42; int* intPtr = &val; cout << "val: " << val << endl; // displays 42 cout<<"*intPtr: "<<*intPtr<<endl;//displays 42 val = 999; cout << "val: " << val << endl;// displays 999 cout << "*intPtr: " << *intPtr << endl; // displays 999

Pointers You can declare a pointer to any type, not just int: char ch= ‘H’; char* chPtr = &ch; cout << “ch: " << ch<< endl; cout << “chPtr: " << chPtr << endl; cout << "*chPtr: " << *chPtr << endl; *chPtr = "!"; cout << "*chPtr: " << *chPtr << endl; cout << “ch: " <<ch<< endl;

Pointers float val = 1.43; float* fltPtr = &val; cout << “val: " << val << endl; // 1.43 cout << “val: " << fltPtr<< endl; // address cout << "*fltPtr: " << *fltPtr << endl; // 1.43 *fltPtr = ; cout << "*fltPtr: " << *fltPtr << endl; // cout << “val: " << val << endl; //

Pointers and const Pointers can be declared const in three ways: The pointer itself can be declared const The data the pointer points (“the pointee”) can be declared const Both the pointer and the pointee can declared const

Pointers and const const pointer, which means that once initialized it can't point at something else. int val1 = 42; int * const intPtr = &val1; *intPtr = -1; // okay int val2 = 999; intPtr = &val2; // error!

Pointers and const const data, which means that the data that the pointer points to can't be changed int val1 = 42; const int * intPtr = &val1; *intPtr = -1; // error! int val2 = 999; intPtr = &val2; // okay

Pointers and const Both of the above -- you can change neither the pointer nor the data it points to: int val1 = 42; const int * const intPtr = &val1; *intPtr = -1; // error! int val2 = 999; intPtr = &val2; // error!

The variety of ways that you can use const can be confusing. One useful way to understand pointer declarations is to read them starting from the variable name reading from right to left. int * intPtr; //the variable intPtr is a pointer to an int. const int * intPtr;//the variable intPtr is a pointer to an int //that is constant. Since the int is constant, we can't change it. We //can change intPtr, however. int * const intPtr;//the variable intPtr is a constant pointer //to an int. Since intPtr is constant, we can't change it. However, we //can change the int. const int * const intPtr; //the variable intPtr is a constant pointer to // an int that is constant. Everything is constant. Pointers and const

Example int main ( ) { int x=4, y=7; int *px, *py; px = &x; //int *px=&x; py = &y; //int *py=&y; cout << “x = ” << x<<“y =”<<y; *px = *px + 10; *py = *py + 10; cout << “x = ” << x<<“y =”<<y; return 0; }

Discussion int main (void) { int a; int *ptr1; char c; char *ptr2; int fred; ptr2=&c; ptr1=&fred; ptr1=&a ; //ok. Char pointer init with add of a char //ok. int pointer init with the address of an int

Discussion ptr2=&fred; ptr2=&'#'; ptr2=&25; ptr2=&(a +3); } // NO. cannot assign the address of an int to a char // NO. cannot take the address of an implicit constant // NO. cannot take the address of an expression

Discussion int main() { int c,a=10; int *p1=&a; c=*p1; *p1=*p1**p1; (*p1)++; c=*&a; } //equivalent expression "c=a" //equivalent expression "a=a*a" //equivalent expression "a++" //equivalent expression "c=a"

Discussion int a = 3; int b = 4; int *pointerToA = &a; int *pointerToB = &b; int *p = pointerToA; p = pointerToB; cout<< a << b << *p ; // Prints 344

Pointer to Pointer int k=4,*ptr, **ptoptr; ptr=&k ptoptr=&ptr; USE Creation of dynamically sizeable arrays Use of new and delete

int main () { int x = 1; int *px = &x; int **ppx = &px; cout << "x = " << x << endl; *px = x+10; cout << "x = " << x << endl; **ppx = *px + x; cout << "x = " << x << endl; return 0; }

int main () { int x = 1; int *px = &x; int **ppx = &px; cout << "x = " << x << endl; *px = x+10; cout << "x = " << x << endl; **ppx = *px + x; cout << "x = " << x << endl; return 0; }

Reference Arguments Reference is an alias to a variable. Reference arguments are indicated by ‘&’ after the data type, e.g. float& x The ‘&’ indicates that ‘x’ is an alias to whatever variable is being passed as an argument. So, power(base, exp); //function call void power(float& x, float& y) // function header ‘x’ is a reference to the float type variable ‘base’ being passed to the function.

Reference Arguments Usage: Passing arguments (both scalar and array) to functions. Advantages: The actual variable can be accessed instead of its copy. Provides a mechanism for returning more than one value from the function back to the calling program. Disadvantages: It allows the function to make changes in the original variable so caution must be taken while passing by reference.

Passing a Variable By Reference void power(float&, int); // prototype void main(void) {float base, int exp =3; cout<< "enter the number whose power you want to find"; cin >> base; power(base, exp); cout <<"result = " <<base ; } void power(float& x, int y) { int product=1; for(int j=1; j<=y; j++) product=product*x; X=product; } Prototype includes & function call is the same header includes &

Pointers and Referencing Reference and pointers have a more or less similar function. However, there are some fundamental differences in how they work. Reference is an alias to the variable, while pointer gives the address of the variable. References basically function like pointers that are dereferenced every time they are used.

Pointers and Referencing However, because you cannot directly access the memory location stored in a reference (as it is dereferenced every time you use the reference), you cannot change the location to which a reference points, whereas you can change the location to which a pointer points.

Pointers and Functions /* test function that returns two values */ void rets2 (int*, int* ); /*prototype*/ int main ( ) {int x, y; /* variables*/ rets2 ( &x, &y ); /*get values from function*/ cout <<“First is = ”<< x<<“Second is = ”<<y; } /* returns two numbers */ void rets2 ( int* px, int* py ) { *px= 3; /* set contents of px to 3 */ *py = 5; /* set contents of px to 5 */ }

Pointers and Arrays In c++, you can treat pointers and arrays very similarily: int array[ ] = {3,1,4,1,5,9}; int* arrayPtr = array; cout<<"array[0]: ” <<array[0] << endl;//displays 3 cout<<"arrayPtr[0]: "<<arrayPtr[0]<<endl;//displays 3 arrayPtr++; cout<<"arrayPtr[0]: "<<arrayPtr[0]<<endl; // displays 1 array++; // error: arrays are const

Pointers and Arrays Arrays and pointers may be used interchangeably, but you can change what pointers point at, whereas arrays will always "point" to the same thing.

Pointers and Arrays // Using pointers to print out values from array int main ( ) {int nums [5] = {92,81,70,69,58}; int dex ; for ( dex = 0; dex <5; dex++ ) cout << *(nums + dex)<<“ ”; } * ( nums + dex ) is same as nums [ dex ].

Pointers and Arrays int * ptr; /* pointer to int (or int array) */ char *chptr; /*pointer to char(or char array)*/ int table[3]= {5, 6, 7}; /* array */ ptr = table; //&table[0]//*assign array address to pointer*/ cout << *ptr; /*prints 5*/ cout << *(ptr+1); /* prints 6 */

Multi Dimensional Arrays (Matrices) An array can have two or more dimensions. This permits them to model multidimensional objects, such as graph paper or the computer display screen. They are often used to represent tables of values consisting of information arranged in rows and columns.

Multi Dimensional Arrays (Matrices) To identify a particular element, we must specify two subscripts. By convention, array_name[row_number][col_number] For example, arr[i][j]

2-D Array (Matrix)

Initializing a 2D Array int matrix [10] [2] = { {59, 78}, {14, 17}, {68, 28}, {32, 45}, { 5, 14}, {12, 15}, { 6, 2}, { 22, 1}, {14, 16}, { 2, 58} }; The values used to initialize an array are separated by commas and surrounded by braces.

2-D Array (Matrix) 59 (0,0) 78 (0,1) 14 (0,2) 17 (0,3) 68 (1,0) 28 (1,1) 32 (1,2) 45 (1,3) 5 (2,0) 14 (2,1) 12 (2,2) 15 (2,3) 6 (3,0) 2 (3,1) 22 (3,2) 1 (3,3) 4 x 4 Matrix int matrix [4] [4] = { {59, 78,14, 17},{68, 28,32, 45}, {5, 14,12, 15},{6, 2, 22, 1} }; (row = 2, col = 0)

Reading a 2D Array int matrix [4][4]={{59,78,14,17},{68,28,32,45}, {5, 14,12,15},{6,2, 22, 1}}; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { cout<<matrix[i][j]<<"\t"; } cout<<endl; }

Example Write a matrix with following entries

Task!! Device a code for filling a 2-D matrix

int main(void) { int matrix[5][2]; for(int i=0;i<5;i++) for(int j=0;j<2;j++) { cout >matrix[i][j]; } cout<<"the input matrix is \n"; for(int i=0;i<5;i++) { for(int j=0;j<2;j++) cout<<matrix[i][j]<<"\t"; cout<<endl; }

Pointers to 2D Arrays b[5] => *(b+5) int a[5][5]; a[2][2] => *(*(a+2)+2)

const int ROWS = 3; const int COLS = 3; int main () { int arr[ROWS][COLS] = {1,2,3}, {2,4,6}, {3,6,9}}; for (int i = 0; i <ROWS; i++) { for(int j = 0; j < COLS; j++) cout << *(*(arr+i)+j) << " "; cout << endl; } return 0; }

Equivalent Expressions int a[n][m]; a[n][m] *(*(a+n)+m) *(a[n]+m) (*(a+n))[m]