Variables and memory addresses

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

Programming and Data Structure
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Kernighan/Ritchie: Kelley/Pohl:
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
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.
Pointers and References (1) THE REFERENCE OPERATOR REFERENCES POINTERS THE DEREFERENCE OPERATOR DERIVED TYPES RETURNING A REFERENCE.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Programming Pointers. COMP104 Lecture 32 / Slide 2 Pointers l Pointers are objects whose values are the locations of other objects l Pointers are memory.
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 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
Pointer Data Type and Pointer Variables. Objectives: Pointer Data Type and Pointer Variables Pointer Declaration Pointer Operators Initializing Pointer.
Pointer Data Type and Pointer Variables II By: Nouf Aljaffan Edited by : Nouf Almunyif.
CSE1222: Lecture 3The Ohio State University1. Assignment Operations  The C++ assignment operator is: =  Examples: x = 3 * 5; y = x – 7; y = y + 4; Do.
Dynamic memory allocation and Pointers Lecture 4.
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.
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.
CS 261 – Data Structures Introduction to C Programming.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT9: Pointer I CS2311 Computer Programming.
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.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9-1 Pointer Variables Pointer variable : Often just called a pointer, it's.
Pointers. What Is Pointer l every variable has memory address char c=’y’; int i=2; address of variable i is 0022 l address can used to refer to this variable.
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.
CSCI 125 & 161 / ENGR 144 Lecture 16 Martin van Bommel.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Windows Programming Lecture 03. Pointers and Arrays.
Pointers as arrays C++ Programming Technologies. Pointers vs. Arrays Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable.
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.
Pointers What is the data type of pointer variables?
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
UNIT 5 C Pointers.
Pointers.
Pointers and Pointer-Based Strings
Student Book An Introduction
Object Oriented Programming COP3330 / CGS5409
Lecture 18 Arrays and Pointer Arithmetic
7 Arrays.
Overloading functions
Pointers and Pointer-Based Strings
Data Structures and Algorithms Introduction to Pointers
Pointers and dynamic objects
Programming Fundamental
Introduction to Pointers
Presentation transcript:

Programming in C++ Pointers & References EEE 145 Programming in C++ Pointers & References

Variables and memory addresses Computer memory can be considered as a very large array of bytes. For example a computer with 1GB of RAM actually contains an array of 1024×1024×1024= 1,073,741,824 Bytes 0=0x00000000 1,073,741,824=0x3fffffff

Variables and memory addresses When a variable is declared and assigned to a value four fundamental attributes associated with it: its name its type its value (content) its address e.g. int n=25; 25 0x0024fdf0 n int

Variables and memory addresses In C/C++ the address operator & returns the memory address of a variable. #include <iostream> using namespace std; int main(){ int n=32; cout<< "n= " << n << endl; cout<< "&n= " << &n << endl; return 0; } Output: n= 32 &n= 0x0024fdf0

References The reference is an alias, a synonym for a variable. It is decelerated by using the reference operator &. #include <iostream> using namespace std; int main(){ int n=32; int &r=n; //r is a reference for n cout << n << " " << r <<endl; --n; r*=2; cout << &n << " " << &r <<endl; return 0; } 32 0xbfdd8ad4 n,r int Output: 32 31 62 0xbfdd8ad4 0xbfdd8ad4

C++ References vs Pointers References are often confused with pointers but three major differences between references and pointers are: You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time.

References #include <iostream> using namespace std; void swap(double &x,double &y){ double z; z=x; x=y; y=z; } int main(){ double a =11.1, b=22.2; cout<<a <<" " << b << endl; swap(a,b); return 0; Output: 11.1 22.2 22.2 11.1

Null pointers It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream.

Null pointers Consider the following program: #include <iostream> using namespace std; int main () { int *ptr = NULL; cout << "The value of ptr is " << ptr ; return 0; } When the above code is compiled and executed, it produces the following result: The value of ptr is 0

Null pointers To check for a null pointer you can use an if statement as follows: if(ptr) // succeeds if p is not null if(!ptr) // succeeds if p is null

Pointer arithmetic As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and –

Incrementing a Pointer #include <iostream> using namespace std; const int MAX = 3; int main (){ int var[MAX] = {10, 100, 200}; int *ptr; ptr = var; for (int i = 0; i < MAX; i++){ cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr++; } return 0; Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200 19

Decrementing a Pointer #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; ptr = &var[MAX-1]; for (int i = MAX; i > 0; i--) cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr--; } return 0; Address of var[3] = 0xbfdb70f8 Value of var[3] = 200 Address of var[2] = 0xbfdb70f4 Value of var[2] = 100 Address of var[1] = 0xbfdb70f0 Value of var[1] = 10 20

Pointer comparisons Address of var[0] = 0xbfce42d0 #include <iostream> using namespace std; const int MAX = 3; int main (){ int var[MAX] = {10, 100, 200}; int *ptr; ptr = var; int i = 0; while ( ptr <= &var[MAX - 1] ){ cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr++; i++;} return 0; } Address of var[0] = 0xbfce42d0 Value of var[0] = 10 Address of var[1] = 0xbfce42d4 Value of var[1] = 100 Address of var[2] = 0xbfce42d8 Value of var[2] = 200 21

Pointers vs. arrays Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing . Consider the following program:

Pointers vs. arrays #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr; ptr = var; for (int i = 0; i < MAX; i++){ cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; ptr++; } return 0; Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200 23

Pointers vs. arrays #include <iostream> using namespace std; However, pointers and arrays are not completely interchangeable. For example, consider the following program: #include <iostream> using namespace std; const int MAX = 3; int main (){ int var[MAX] = {10, 100, 200}; for (int i = 0; i < MAX; i++){ *var = i; // This is a correct syntax var++; // This is incorrect. } return 0; It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value.

Pointers vs. arrays Because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified. For example, the following is a valid statement that assigns var[2] the value 500: *(var + 2) = 500; Above statement is valid and will compile successfully because var is not changed.

Array of pointers There may be a situation, when we want to maintain an array, which can store pointers to an int or char or another data type available. Following is the declaration of an array of pointers to an integer: int *ptr[MAX]; This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. Following example makes use of three integers which will be stored in an array of pointers as follows:

Array of pointers #include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *ptr[MAX]; for (int i = 0; i < MAX; i++){ ptr[i] = &var[i]; } cout << "Value of var[" << i << "] = "; cout << *ptr[i] << endl; } return 0; Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200 27

Passing pointers to functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type. Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function:

Passing pointers to functions in C++ #include <iostream> #include <ctime> using namespace std; void getSeconds(unsigned long *par); int main (){ unsigned long sec; getSeconds( &sec ); cout << "Number of seconds :" << sec << endl; return 0; } void getSeconds(unsigned long *par) { // get the current number of seconds *par = time( NULL ); return; Number of seconds :1294450468 29

Passing pointers to functions in C++ #include <iostream> using namespace std; double getAverage(int *arr, int size); int main (){ int balance[5] = {1000, 2, 3, 17, 50}; double avg; avg = getAverage( balance, 5 ) ; cout << "Average value is: " << avg << endl; return 0; } double getAverage(int *arr, int size){ int i, sum = 0; for (i = 0; i < size; ++i){ sum += arr[i]; avg = double(sum) / size; return avg; Average value is: 214.4 30

Return pointer from functions in C++ As we have seen before how C++ allows to return an array from a function, similar way C++ allows you to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example: int * myFunction() {. . } Second point to remember is that, it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable. Now, consider the following function, which will generate 10 random numbers and return them using an array name which represents a pointer i.e., address of first array element.

Return pointer from functions in C++ #include <iostream> #include <ctime> using namespace std; int * getRandom( ){ static int r[10]; srand( (unsigned)time( NULL ) ); for (int i = 0; i < 10; ++i){ r[i] = rand(); cout << r[i] << endl; } return r; int main (){ int *p; p = getRandom(); for ( int i = 0; i < 10; i++ ){ cout << "*(p + " << i << ") : "; cout << *(p + i) << endl; return 0; 624723190 1468735695 807113585 976495677 613357504 1377296355 1530315259 1778906708 1820354158 667126415 *(p + 0) : 624723190 *(p + 1) : 1468735695 *(p + 2) : 807113585 *(p + 3) : 976495677 *(p + 4) : 613357504 *(p + 5) : 1377296355 *(p + 6) : 1530315259 *(p + 7) : 1778906708 *(p + 8) : 1820354158 *(p + 9) : 667126415 32