Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Programming and Data Structure
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
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.
Writing a Good Program 6. Pointers and Arrays
Chapter 10.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
C arrays (Reek, Ch. 8) 1CS 3090: Safety Critical Programming in C.
Pointers Applications
Review of C++ Programming Part II Sheng-Fang Huang.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
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 CSC241: Object Oriented Programming Lecture No 22.
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.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
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.
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.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Scis.regis.edu ● CS-362: Data Structures Week 6 Part 2 Dr. Jesús Borrego 1.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Learners Support Publications Constructors and Destructors.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Windows Programming Lecture 03. Pointers and Arrays.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Constructors and Destructors
Dynamic Storage Allocation
Pointers and Dynamic Arrays
Pointers and Dynamic Arrays
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 10: Pointers 1.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Arrays and Pointers Reference: Chapter , 4.11 CMSC 202.
Dynamic Memory Allocation
Constructors and Destructors
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
Presentation transcript:

Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer “points” to the other variable in memory A pointer is declared using the general statement: type *name;e.g.int *i1;

Important Uses of Pointers Allows functions to modify their arguments Supports dynamic memory allocation functions Improves the efficiency of certain routines Allows communication to other functions, programs, and hardware using shared memory and memory transfers Pointers are one of the most powerful features of C/C++ but are also the most dangerous

Pointer Operators &breturn the memory address of variable b *preturn the value of the variable at address p * is the complement of & so that *(&b)=b These operators have a higher precedence than other arithmetic operators except urinary minus which is equal int b = 7777, *p; p = &b; cout << *p;  7777

A Variable Pointing to Another Variable Memory addressVariable in memory p i1 *p

Pointer Expressions p = qpointer assignment p++, p--increment and decrement p = p + iaddition of an integer i p = p - isubtraction of an integer i p == qtest for equality p qpointer comparison

char *ch = 3000; int *i = 3000; expressionMemory (bytes) expression ch3000i ch ch ch ch i + 1 ch

Pointers and Arrays A 1D array is equivalent to a pointer to the first element There are two ways of accessing arrays:  pointer arithmetic and array indexing, s1[i]=*(s1+i) Indexing can also be used on pointer variables char s1[6] = “peach”, *p1; p1 = s1; cout << s1[3] << *(p1+3) << p1[3] << *(s1+3);  cccc

Passing Pointers and Arrays to Functions 1D arrays and pointers are interchangeable when passing arguments to functions Since the memory location is passed to the function it will modify the contents of the array: call by reference No copies of the array are made when passed to the function Be sure to know the boundaries of the array to avoid invalid memory access

Modifying Function Arguments Pointers allow C functions to modify their arguments call by value int i = 0; fun1(i); cout << i;  0 call by reference int i = 0; fun2(&i); cout << i;  7777 void fun1(int i) { i = 7777; } void fun2(int *i) { *i = 7777; }

Array Swapping int ar[2]={1,2}, br[2]={3,4}; int *a=ar,*b=br,*c; c = a;a = b; b = c; cout << a[0] << a[1] << “\n”;34 cout << b[0] << b[1];  12 This is more efficient than swapping each element Make sure you swap any dimension information too

Initializing Pointers Always initialize your pointers to valid memory locations A pointer initialized incorrectly is called a wild pointer Reading data from a wild pointer will return garbage Writing data to a wild pointer could overwrite program, data or operating system memory, e.g. int x, *p; x = 10; *p = x;

Common Problems With Pointers int x, *p; x = 10; p = x; cout << *p;  improper usage char a[10], b[10]; char *p1, *p2; p1 = a; p2 = b; if (p1 < p2) … two arrays will not be stored in any particular order

Dynamic Memory Allocation static arrays allocate memory at the beginning of program execution char s1[10], *p1; p1 = s1; dynamic memory is allocated during program execution #include char *p1; p1 = (char *)malloc(10*sizeof(char));

Dynamic Arrays Dynamic arrays are useful because the size of the array can be determined at run-time The size of the array can be made just small enough for the application The memory allocated can also be freed for other functions to use when it is no longer needed It must be freed before the program is finished using the function free(p1)

New and Delete Operators C++ provides operators for dynamic memory allocation p = new type [size];// new operator for allocation delete p; // delete operator for freeing memory int *p1; char *p2; p1 = new int;p2 = new char [5]; *p1 = 8;strcpy(p2,”ball”); cout << *p1 << p2; delete p1; delete p2;  8ball

Comparison with C Allocation Routines New and delete have the following advantages over malloc and free: Automatically computes the size needed in bytes Automatically returns a pointer of a specified type Provides support for C++ features related to operator overloading, initialization, constructors, and destructors Note that both malloc and new can take longer to run than static memory allocation for large blocks of memory

Arrays of Pointers Arrays of pointers can be declared like any other type char *pa[2]; char p1[]="hello", p2[]="goodbye"; pa[0] = p1;pa[1] = p2; cout << "\n" << pa[0] << "\t" << pa[1]; cout << "\n" << *(pa[0]+1) << "\t" << *(pa[1]+1); cout << "\n" << pa[0][1] << "\t" << pa[1][1]; This is useful for developing multidimensional arrays

pa pa[0] pa[1] memory addressvariable E 1008‘h’ 1009‘e’ 100A‘l’ 100B‘l’ 100C‘o’ 100D‘\0’ 100E‘g’ 100F‘o’

Pointers to Pointers Since pointers are stored in memory we can declare pointers to them as well char **pp; char *p, s[]="MJ"; p = s; // point to the string pp = &p; // get the pointer to p cout << "\n" << p << "\t" << *pp; cout << "\n" << *(p+1) << "\t" << *(*pp+1); A pointer to a pointer is the same as an array of pointers

memory addressvariable ‘M’ 1009‘J’ pp p, s **pp *pp

pa pa[0] pa[1] memory addressvariable E 1008‘h’ 1009‘e’ 100A‘l’ 100B‘l’ 100C‘o’ 100D‘\0’ 100E‘g’ 100F‘o’ pp pp[0] pp[1]

Function Pointers Functions also have memory locations so we can define function pointers to them as follows double (*pf)(double x); // declare a function pointer pf = &f1; // initialize pointer cout << "\nf1 = " << (*pf)(3);  9 double f1(double x) { return (x*x); } This is very useful for passing functions to other functions

Why Pointers ? Allows functions to modify their arguments Supports dynamic memory allocation functions Improves the efficiency of certain routines (swapping, …) Allows communication to other functions, programs, and hardware using shared memory and memory transfers Useful for passing functions to other functions Important for developing multidimensional dynamic arrays

Review A 1D array is the same as a pointer to the first element double s[2] = { 1.0, 2.0 }, *p; p = s; p[1] == s[1] == *(p+1) == *(s+1) == 2 We can dynamically allocate a 1D array using new double *p;int n = 10; p = new double [n]; p[1] = 1.0; delete p; We can also have a 1D array of pointers which is the same as a pointer to a pointer double *pa[10], **pp;pp = pa;

Questions 1.Initialize a 1D dynamic array of doubles from a file. Use new / delete (or malloc / free if CC is defined). example file: Load an array of vectors (3d) from a file and store them in dynamic memory using an array of pointers (hint: each element will point to a different vector). example file:

More on Static Multidimensional Arrays 2D static arrays are stored in a row by row format int a[2][3] = {1,2,3,4,5,6};  a = int *r0, *r1, i; r0 = a[0]; r1 = a[1]; for(i=0;i<6;i++) cout << r0[i] << “ ”;  for(i=0;i<3;i++) cout << r1[i] << “ ”; 

Limitations of Static Multidimensional Arrays They cannot be passed to general functions since arrays of different sizes cannot be used interchangeably int a[4][4]; a[0][0] = 1; f1(a);  can’t convert int[4][4] to int[][3] int fun1(int a[3][3]) { return a[0][0]; } They also cannot be converted to a pointer to pointer Only use static multidimensional arrays for simple applications where the size is always fixed

Multidimensional Dynamic Arrays One way to construct a 2D dynamic array: First allocate a 1D dynamic array of pointers This will have a pointer to pointer type Then initialize each array element to a 1D dynamic array that stores each row  done ! Dynamic arrays of any size can be passed to a function since they all have pointer to pointer type

Row Swapping Rows of a dynamic array can be efficiently swapped by swapping the pointers to the rows int *pa[2], **m, r0[] = {1,2}, r1[] = {3,4}, *d; m = pa; m[0] = r0; m[1] = r1; cout << m[0][0] << m[0][1] << “\n” << m[1][0] << m[1][1]; d = m[0]; m[0] = m[1]; m[1] = d; cout << “\n\n”; cout << m[0][0] << m[0][1] << “\n” << m[1][0] << m[1][1];

Pointers to Objects class string_class { public: char str[100]; void strcpy2(char *s); }; void string_class::strcpy2(char *s) { strcpy(str,s); } string_class s1, *sp; s1.strcpy2(“ya”); sp = &s1; cout str;  yayaya

Arrays of Objects string_class s1[3], *sp; s1[0].strcpy2(“one”); s1[1].strcpy2(“two”); s1[2].strcpy2(“three”); sp = s1; cout str << “\n“; sp++;  one cout str << “\n“; sp++;two cout str << “\n”;three cout << sp[0].str;three

Dynamically Allocated Objects string_class *sp1,*sp2; sp1 = new string_class(“apple”); // initialize object to “apple” sp2 = new string_class [3]; // can’t initialize dynamic arrays sp2[0].strcpy2(“peach”); cout str << “ “ << sp2[0].str << “\n”; delete sp1; delete [3] sp2; // need to put [size] first for dyn object arrays string_class::string_class(char *s) { strcpy(str,s); cout << “construct\n”; } // for sp1 string_class::string_class() { cout << “c0\n”; } // for sp2

Constructor Functions A constructor function can be defined that automatically gets called when an object is created, e.g. class string_class { public: string_class(char *s) { cout << “construct\n”; } }; Constructor functions are used to initialize an object (setting variables, allocating dynamic memory, etc.) You should also define a constructor that takes no parameters if you intend to declare an array of objects

Destructor Functions A destructor function can also be defined that automatically gets called when an object is destroyed class string_class { public: ~string_class() { cout << “destruct\n”; } }; Destructors are used to clean up when an object is destroyed (close files, free dynamic memory, etc.) Destructors do not take any parameters

Constructor and Destructor Functions It is important to recognize when objects are created (constructor) and destroyed (destructor) in a program Special care should be taken when dynamic memory is allocated in the constructor and freed in the destructor Repeated new (malloc) and delete (free) statements must be avoided since they can destabilize the program p1 = new double [10]; p1 = new double [10]; // invalid delete p1; delete p1; // invalid

Object Creation and Destruction Global objects are created when the program is initially executed and destroyed when the program ends Local objects are created when the program enters the function and are destroyed when the function returns Dynamic objects are created at the new statement and destroyed at the delete statement When a static or dynamic array of objects is declared an object is created / destroyed for each element in the array Same rules apply for simple variable types (double, etc.)

Object Creation and Destruction Function parameters that are call by value are copied when entering the function, but a constructor is not called Call by value parameters are destroyed when the function returns  the destructor will be called too many times Call by reference parameters are not copied or destroyed by a function Use call by reference for objects that have destructors or dynamic memory. Note that the object can be modified Returning an object will make a copy (no constructor) but the destructor is also called for the returned object

References A reference is an implicit pointer (C++) that basically acts like a second name for a variable References have three main uses: 1. Call by reference function parameters 2. To create an alternative name for a variable 3. Returning a reference from a function The usage of references is much more restricted than a pointer. Don’t bother trying to use them for anything else

Topic Review Pointers Pointers and 1D arrays Dynamic memory Arrays of pointers Pointer to pointers Function pointers Multidimensional Dynamic arrays Pointers to objects and object arrays Constructor and Destructor functions