Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Similar documents
At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

Table of Laplace Transforms

Intermediate Programming, Spring 2017*

EL2310 Scientific Programming

Pointers in C/C++ 1 Memory Addresses 2

Introduction to C: Pointers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

A student was asked to point out interface elements in this code: Answer: cout. What is wrong?

Here's how you declare a function that returns a pointer to a character:

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

QUIZ. What are 3 differences between C and C++ const variables?

Data Structure Series

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

QUIZ. Source:

Software Design and Analysis for Engineers

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Dynamic Data Structures. CSCI 112: Programming in C

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

The Dynamic Typing Interlude

C++ for Java Programmers

CS107 Handout 13 Spring 2008 April 18, 2008 Computer Architecture: Take II

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Lecture 2: C Programm

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Lectures 5-6: Introduction to C

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Pointers. Memory. void foo() { }//return

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

Programming and Data Structures Prof. N. S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Programming in C - Part 2

Pointers, Dynamic Data, and Reference Types

Lab 3. Pointers Programming Lab (Using C) XU Silei

Arrays and Pointers in C. Alan L. Cox

Contents. Slide Set 1. About these slides. Outline of Slide Set 1. Typographical conventions: Italics. Typographical conventions. About these slides

Motivation was to facilitate development of systems software, especially OS development.

Structures and Member Functions

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

COP 3223 Introduction to Programming with C - Study Union - Spring 2018

Goals of this Lecture

Pointers. 10/5/07 Pointers 1

Unit IV & V Previous Papers 1 mark Answers

CSCI 171 Chapter Outlines

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Dynamic Memory Allocation

Pointers II. Class 31

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

Functions, Pointers, and the Basics of C++ Classes

Malloc Lab & Midterm Solutions. Recitation 11: Tuesday: 11/08/2016

CS 61c: Great Ideas in Computer Architecture

BBM 201 DATA STRUCTURES

CS201- Introduction to Programming Current Quizzes

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Lectures 5-6: Introduction to C

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Structures and Pointers

C for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Lecture Topics. Administrivia

Procedures, Parameters, Values and Variables. Steven R. Bagley

by Pearson Education, Inc. All Rights Reserved.

C++ for Java Programmers

A Fast Review of C Essentials Part I

Contents of Lecture 3

QUIZ. What is wrong with this code that uses default arguments?

377 Student Guide to C++

Review of the C Programming Language for Principles of Operating Systems

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

Software Design and Analysis for Engineers

Recitation #11 Malloc Lab. November 7th, 2017

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

CS61C Midterm Review on C & Memory Management

malloc(), calloc(), realloc(), and free()

Heap Arrays and Linked Lists. Steven R. Bagley

6.001 Notes: Section 1.1

Declaring Pointers. Declaration of pointers <type> *variable <type> *variable = initial-value Examples:

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

AIMS Embedded Systems Programming MT 2017

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CS201 Some Important Definitions

CS 430 Computer Architecture. C/Assembler Arithmetic and Memory Access William J. Taffe. David Patterson

Pointers. Reference operator (&) ted = &andy;

Transcription:

Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have to worry where variables are stored With pointers, we have direct access to the management of variables and data 1 Pointer are not hard to understand. Forget anything you ve heard. Pointers are simply a reference to a variable or object (remember the object part for C++). 06-88-211-05-Pointers 1

Pointers When someone talks to you, they speak directly to you This is similar to using a variable You address it directly When someone calls you on the phone, sends you mail, or sends you email This is similar to using a pointer You address information indirectly with the help of another piece of information 2 Up to this point, we have dealt with variables and we have never looked at how the computer stores or manages them to any significant degree. All we know is when we set or read a variable it is done and we don t have to worry about it. Pointers are simply that, they point to something. They are a reference. Think of them as phone numbers, email, etc. They are simply a means to get you to a particular piece of information (information on a computer is data or a variable, in the real world you can look at information as people, places, etc). 06-88-211-05-Pointers 2

Pointers We declare pointers in C to refer to a particular data type or structure/union Do this by placing a * in front of the variable during declaration To read/write a value to where the pointer references, place a * in front of the variable We can determine the address of another variable or pointer using an & (address of) 3 We declare pointers just as any other variable type, except we place a * in front of the variable. This applies to the basic variable types, structures, and unions. Once the pointer is declared, we can change the data of where the pointer points to by placing a * in front of it, just like in the declaration. For example if we declare: int *b; we address what b points to with: *b =. Before we can even address what a pointer points to, we have to be able to assign an address to the pointer itself. We can t call someone if we don t know their phone number. We can obtain the address of a variable by placing a & in front of it. For example: b=&a; where a is an integer, not a pointer to an integer. 06-88-211-05-Pointers 3

Example: Pointers Declare a as integer Declare b as a pointer to an integer Set a to 10 Set b to pointer where a stores it s data void main(void) int a; int *b; a = 10; b = &a; /* b points to where a is stored */ *b = 5; Set the value of where b points to /* a is now 5 */ 4 This example extends on the previous slide. We can first declare a as an integer and b as a pointer to an integer. Since a is a variable, we can set it to some number, we will use 10. b is a pointer to an integer, so must set it to the address of an integer, we will use the address of a, which is &a. b now points to where a stores it s information. We can then change the value of a without actually addressing a itself. By using *b = 5 we can change the value of what b points to. Before this, it was 10, now we change it to 5. 06-88-211-05-Pointers 4

Example: Pointers to Pointers Declare c as a pointer to a pointer ( b ) Set a to 10, then set where b points to (5) Set c to pointer where b stores it s data void main(void) int a, *b, **c; a = 10; b = &a; /* b points to where a is stored */ *b = 5; /* a is now 5 */ Set the value of where the value of c points to c = &b; **c = 1; /* a is now 1 */ 5 No only can we have pointers to variables, but we can have pointers to pointers. This example is to illustrate the concept of a pointer to a pointer. It isn t terribly practical, but we will soon explored practical applications of pointer to pointers. We can further extend the previous example to include a pointer to a pointer c, of type integer. After we change the value of a through b, we can alter a yet again. We assign c the address of b. We can then change the value of a by setting **c. Each * indicates a reference to process. In this case we process the reference c, and then the reference b (since c points to b and b points to a ). You can look at this as a real world example of you wanting to call someone, but you don t have their phone number. So you call a friend who knows the phone number and they subsequently call that person. 06-88-211-05-Pointers 5

Example: Pointers and Arrays Arrays are pointers! A pointer is a reference to some memory location void main(void) int a[10]; /* a is a pointer */ a[0] = 1; *(a+0) = 1; /* same assignment */ The C compiler automatically compensates for arithmetic on a pointer a[5] = 5; *(a+5) = 5; /* same assignment */ /* a[i] is the same as *(a+i) */ 6 Although we never realised it, arrays are pointers. We ve dealt with addressing the contents of arrays (e.g. a[0]) but not the pointers. In this example, a itself is a pointer. By placing the [ ] after it implies we want to address an offset of the pointer. If we want to address a[i], we would really be addressing *(a+i), where i is the element number. This only applies to one-dimensional arrays. We ve already discussed how the computer converters or addresses multi-dimensional arrays into one dimension. The computer refers to memory in terms of bytes. In this case when we use *(a+i), the data type of the pointer is an int or 4 bytes. The compiler automatically does the arithmetic to convert the reference into what the computer understands. In this case, the computer really sees: *(a+i*4) since it addresses memory in terms of bytes. 06-88-211-05-Pointers 6

Example: Pointers and Structures Declare a as a structure Declare b as a pointer to the same structure type as a Set a to 10+j20 Set b to pointer where a stores it s data void main(void) struct _complex double re, im; a, *b; a.re = 10; a.im = 20; /* a is 10+j20 */ b = &a; /* b points to where a is stored */ Set the value of where b points to (5+j15) b->re = 5; b->im = 15; /* a is now 5+j15 */ 7 The individuals who developed C found it necessary to add a new operator to C in order to address the need for using points with structures or unions. In this example, since b is a pointer, we can t just use a dot (. ) to address the members of the complex number. We would first dereference it with a *. However, this is not the preferred method in C. C developers would rather use a -> to reference the member of a structure or union. You can look at -> as removing one of the *. i.e. b->re is the same as (*b).re. I believe the reason is that C places a higher precedence on the. rather than the *, so we must put (*b) in parenthesis as we did. 06-88-211-05-Pointers 7

Example: Pointers and Structures Can also use the zero array method Can also use the pointer method Remember to use the brackets void main(void) struct _complex double re, im; a, *b; a.re = 10; a.im = 20; /* a is 10+j20 */ b = &a; b[0].re = 5; b[0].im = 15; /* a is now 5+j15 */ (*b).re = 6; (*b).im = 16; /* a is now 6+j16 */ 8 Here are the alternatives to using -> entirely. We can use b[0] to dereference the pointer, and then use the. to access the member. Or we can alternatively user (*b) to dereference the pointer and then use. to access the member. Either works, but don t forget the parenthesis. 06-88-211-05-Pointers 8

Example: Pointers and Functions We can create pointers which not only address variables/data but also functions Declare pointer with all argument data types of function int add(int a, int b) return a + b; void main(void) /* declare pointer to function */ int (*func)(int, int); int a; func = &add; Set func equal to the address of the function a = func(10, 20); /* a is 30 */ 9 Since we can have pointers to any data type or structure in C, it makes sense that we can have pointers to functions also. It is important to realize that functions are a piece of code which the computer executes. It is not good practice to set the value of a function unless you are absolutely certain you know what you are doing. Keeping that in mind, you should never place a * in front of a pointer to a function unless you are declaring it. In this example, we first declare a function add. add returns an int (it is placed before the name) and it requires two arguments of type integer ( a and b ). The actual code is simple, it returns the sum of a and b. The calling function (main) declares a pointer to a function by placing the * and variable inside parenthesis, in this case (*func). This is VERY important or else the C compiler will think it is a pointer to a variable and not a function. It is good practice to add the types of arguments that the function will require. This ensures that we will not accidentally set our pointer func to an inadequate function; the C compiler will warn us if we do. We can set the value of func by using the address of or & operator just like we do with other variables. Lastly, we can call func with arguments in the parenthesis to get the appropriate result. 06-88-211-05-Pointers 9

Example: Pointers and References (C++) Declare a as integer Declare b as a reference to integer a Set a to 10 int main(void) int a; int &b=a; a = 10; b = 5; Set b to 5 // a is now 5 a is now 5 10 The above example is the first piece of C++ code we have seen. It isn t much different thus far, but you will notice that in the first line we are returning an int now instead of void. C++ does not allow you to return different data types as C did. If you compiled any C code prior to this using void main(void) the compiler should have given a WARNING that main requires an integer to be returned. C++ strictly enforces this now. Another thing you may have noticed is the //. This is a single line comment. Anything after the // is considered a comment for the rest of the line. This particular example is used to illustrate a new C++ feature known as references. It is basically the same thing as what we ve done previously with pointer. The line int &b=a; says that b is a pointer and it points to where a is stored. This is essentially what we did before, but the difference is if we want to address what b points to, we simply use b. This example is purely illustrative and is not practical. The real use of references will be shown later when we discuss functions. 06-88-211-05-Pointers 10

Pointers and Dynamic Memory We primarily use pointer so that we can address dynamic memory Static memory is when we declare variables and arrays before we compile our code Dynamic memory is allocated as we need it for the storage of variables and arrays Use more or less memory for different applications 11 All of the examples of pointers to now are to illustrate the pointer and the operators you can use to set and dereference them. Realistically we won t be using pointers like we did in those examples. The real reason of understanding and using pointers is so that we can address dynamic memory. Dynamic memory is essential for any problem solving because the amount of memory required to solve a problem can change, not only from problem to problem, but also from stage to stage in a problem. Today, with the affordability of computers, we can solve many more complex engineering problems than we could 5 years ago. However, there are still problems we can t solve because our computers are too slow, or simply don t have enough memory. We know how to solve these problems, we just can t, yet. Eventually we will be able to do this as memory and processing speeds increase, but for those applications that we need to solve, we have to manage memory better. Computer operating systems (Windows, UNIX, etc.) manage the memory for us since there are so many other program running on a particular computer. All programs communicate to the operating system for all operations such as memory allocation, file/disk access, network access, etc. 06-88-211-05-Pointers 11

Dynamic Memory (C++) Declare variables, arrays and pointers Allocate space for b Set b using * or first array notation int main(void) int a, *b, c[100], *d; a = 100; // allocate b b = new int; *b = 10; b[0] = 10; Allocate space for d 100 integers Set d using * or array notation De-allocate b and d // allocate array d d = new int[a]; d[10] = 10; // or *(d+10) = 10; // de-allocate memory delete b; delete d; 12 Here is an example of using dynamic memory in C++. We have the ability to use dynamic memory in C also, however, this depends on library calls (malloc, calloc, realloc, free) that require several parameters that C++ takes care of for us. In this example, we define a couple types of integers, a which is just a standard variable, b is a pointer to an integer, c is a static array of 100 elements and d is another pointer to an integer. As the program flows, we can set a to any integer value, we choose 100 in this case. Since b is a pointer, we must assign an address to it first before we can use it for any storage. Here we use a new C++ keyword known as new. It allocates memory for the data type we specify, in this case an integer. b is now assigned an address which points to a place in memory that has been given to us. We can then store an element in b using either the pointer method or array method for dereferencing the pointer. We can do the same for d since it is also a pointer. In this example, we will allocate an ARRAY for d. We do that by simply using the new keyword along with a value in square brackets, a in this case, to indicate the number of elements in the array. We could us anything in the square brackets as long as it resolves to a number. In C we couldn t have used a variable, this isn t allowed for static arrays, but in C++ we can and therefore have created a dynamic array the size can change as the program inputs change. After allocation, we can access parts of the array with the pointer method or the array method. The array method is the same if we were using static arrays. All good programmers should clean up after themselves. C++ provides the delete keyword to un-allocate the memory which you have previously located. It only removes memory which you obtained through the new keyword. b and d in this case are still pointers, but they point to invalid information after the delete is executed. 06-88-211-05-Pointers 12

Dynamic Memory and Arrays Create a list of pointers Each element points to a row #define rows 10 #define cols 10 int main(void) int i; double **m; Create a onedimensional array for each row Can address using compile-time methods // alloc ptr to cols m = new double * [rows]; // alloc each row for(i=0;i<rows;i++) m[i]=new double[cols]; // m[r][c] =? // de-alloc for(i=0;i<rows;i++) delete m[i]; delete m; 13 This is the basic template of code we will be using when dealing with matrices. This may look very different from before when we dealt only with double m[rows][cols], for example, but it will actually process quicker and we can interact with it the same way as we did with static arrays. First we declare a pointer to a pointer m. Don t worry about the fact that it is a pointer to a pointer, that will become more apparent later. Just visualize the organization as this: Previously when dealing with static arrays the computer would perform the calculations to convert our two-dimensional array into a one-dimensional array. We saw how this happens earlier. The problem with this, not just that it is a static array, the array can be large and continuous. The array, in the case of a double, would be 8*rows*cols continuous bytes. As rows and cols gets bigger, the demand for a single piece of continuous memory becomes larger. What we will do here is break up the matrix into rows, so that each row is a separate piece of memory. This relieves the strain on the operating system to provide a large chunk of memory down to a fraction of that. Now our largest chunk of memory will be 8*cols, but we will have rows of them. This is easier to manage, not just by the point of view of the computer, but also for us. One of the most useful abilities when dealing with matrices is to be able to switch rows. By allocating row by row, we can easily switch rows. 06-88-211-05-Pointers 13

Dynamic Memory and Arrays Double ( cols elements) **m Double * ( rows elements) 14 Here is a visual interpretation of what is happening in the code. First we have **m, shown above as a single box. This memory which holds the value of **m is allocated by the compiler, it is the pointer to a pointer, a 32- bit unsigned integer just like any other. Why it is a pointer to a pointer will be apparent soon. In the end though, we need to be able to access a series of rows, each of which contain columns of numbers. We therefore need the list of rows before the can get to the columns. So we use the new operator to allocate memory for an array of rows elements of type double *, described as the single column above. m now points to this array. Now we have a list which we can use to store the addresses to each row. We can then use a loop, rows times, to allocate memory for the arrays of rows, each with cols elements in them. This is where the numbers of the matrix are actually stored. Since this is where the data is stored we know whatever points to them should be a pointer, double *, which is the type used for the column array. And since m itself must point to this array, m is therefore a pointer to a pointer. It is sometimes best to work out points backwards to understand the levels of pointers to pointers required. When addressing this matrix, we use m[r][c], where r is the rows and c is the column. The double brackets de-references the pointer to pointer m. The m points to the row matrix and this is indexed by r. For example, setting r=0 selects the first row The c the indexes the particular column of the specific row. Although this is very different from static arrays, it operates exactly as it would have with static arrays. 06-88-211-05-Pointers 14

Example: Dynamic Memory & Arrays Can exchange rows easily without copying the actual values double **m; double *t; Ideal for finding the inverse of a matrix This can be used in many applications /* Exchange row 2 & 4 */ t = m[2]; m[2] = m[4]; m[4] = t; 15 One of the reasons we used this matrix data structure is so that we can easily exchange the rows of the matrix. This is a key requirement when performing any inversion operation. Since we developed the data structure so that each row is separate from the other rows, and that these rows are indexed by an array of pointers, we can simply swap two of these row pointers. The code above illustrates the simplicity of this operation. Assume this code is part of the previous code, we can see the definition of m as **m. m points to our list of addresses, each of which specifies the location of a row. We also declare t as *t, which is the same as the elements found in the array which m points to; they must be the same. t is a temporary variable, that is it s only purpose. In the above example, we are exchanging rows 2 and 4. We do this by first noting where row 2 exists in memory, or it s pointer. We save row 2 s pointer into t. We then move the value of row 4 s pointer into row 2 s. Now row 2 and row 4 point to the same row. Finally, we write the location of row 2, currently in t, into where the pointer of row 4 is. This is the exchange or swapping of two rows. If this were a static array we would have to exchange each element in both rows with each other. If the number of columns in the rows is large, this can be a very costly operation especially if it is to be done thousands of times. 06-88-211-05-Pointers 15

Example: Dynamic Memory and Structures Can use dynamic memory on structures and unions just like any other basic data type int main(void) typedef struct double re, im; complex; complex *a, *b; Can also apply to arrays Easier when using typedef a = new complex; b = new complex[10]; a->re = 10; a->im = 20; // a is 10+j20 b[0].re = 1; b[0].im = 2; 16 Just as we are able to apply dynamic memory to basic C data types (double, ints, etc.), we can also apply it to our own custom types. This example shows our complex number structure, aliases using a typedef. We declare two pointers a and b to the complex type. We can then user the new command to allocate memory for a single element (as in the case of a ) or for an array of elements (as in the case of b ). Since a is a pointer, we must use the -> notation to address the members of the structure. We can also use a[0].re, a[0].im if you prefer to use the dot notation. The [0] dereferences the pointer, just as *(a).re, *(a).im would. In the case of b, we use the array notation since b points to an array of elements. We could also use *(b+i).re, *(b+i).im, where i is the index. We can also see that typedef becomes more useful as it eliminates extra code. 06-88-211-05-Pointers 16