MEMORY ADDRESS _ REPRESENTATION OF BYTES AND ITS ADDRESSES

Similar documents

Kapi ap l S e S hgal P T C p t u er. r S. c S ienc n e A n A k n leshw h ar ar Guj u arat C C h - 8

Chapter-11 POINTERS. Important 3 Marks. Introduction: Memory Utilization of Pointer: Pointer:

What is Pointer? Pointer is a variable that holds a memory address, usually location of another variable.

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?


[0569] p 0318 garbage

C++ for Java Programmers

CS201- Introduction to Programming Current Quizzes

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Pointers, Dynamic Data, and Reference Types

Darshan Institute of Engineering & Technology for Diploma Studies

Short Notes of CS201

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

! A pointer variable (or pointer): ! An asterisk is used to define a pointer variable. ! ptr is a pointer to an int or

CS201 - Introduction to Programming Glossary By

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Pointers and Dynamic Memory Allocation

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

Pointer Data Type and Pointer Variables

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

Arrays, Pointers and Memory Management

POINTERS. Pointer is a memory variable which can store address of an object of specified data type. For example:

Dynamic Memory Allocation

Object Oriented Pragramming (22316)

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

Homework #3 CS2255 Fall 2012

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Language comparison. C has pointers. Java has references. C++ has pointers and references

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

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

Pointers. Variable Declaration. Chapter 10

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Overloading Operators

Exam 3 Chapters 7 & 9

Pointers II. Class 31

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

Scott Gibson. Pointers & Dynamic Memory. Pre & Co Requisites. Random Access Memory. Data Types. Atomic Type Sizes

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

SYSC 2006 C Winter 2012

CS201 Some Important Definitions

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Pointers. Introduction

Structured Data. CIS 15 : Spring 2007

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Lectures 6/7 Pointers and Dynamic Arrays

Unit IV & V Previous Papers 1 mark Answers

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Pointers! Arizona State University 1

Lecture 2: C Programm

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

Programming Studio #9 ECE 190

Lecture 8: Pointer Arithmetic (review) Endianness Functions and pointers

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

Chapter-13 USER DEFINED FUNCTIONS

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Syntax to define a Structure: struct structurename { datatype membername1; datatype membername2;... } ; For Example:

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

Cpt S 122 Data Structures. Data Structures

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

C++ Programming. Pointers and Memory Management. M1 Math Michail Lampis

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Arrays and Pointers (part 1)

Chapter 6 Pointers and Arrays

Assist. Prof. Dr. Caner ÖZCAN

Arrays and Pointers (part 1)

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

Functions. Introduction :

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Procedural programming with C

CS2141 Software Development using C/C++ C++ Basics

DECLARAING AND INITIALIZING POINTERS

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

Pointers and File Handling

Introduction to C Language (M3-R )

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Dynamic Allocation of Memory

In Java we have the keyword null, which is the value of an uninitialized reference type

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Computer Programming

CSCI 171 Chapter Outlines

Arrays and Linked Lists

Section - Computer Science. int main() {! int a=10,b=20;! printf("a:%d B:%d\n",a,b);! a=(a+b)-(b=a);! printf("a:%d B:%d\n",a,b);!

Solution: A pointer is a variable that holds the address of another object (data item) rather than a value.

Transcription:

[1] ~~~~~~~~~~~~~~~~~ POINTER A pointers is a variable that holds a memory address, usually the location of another variable in memory. IMPORTANT FEATURES OF POINTERS (1) provide the means through which the memory location of variables can be directly accessed and they can be manipulated at wish. (2) support C++ s dynamic allocation routines. (3) improve the efficiency of certain routines. Note: Every byte of computer s memory (internal) has an address. For 280 KB = 280*1024 bytes = 286720 bytes. addresses of each bytes is allocated as mentioned in the figure: MEMORY ADDRESS 0 1 2 3 4 _- - - - - - - - - - - - - - - - - 286717 286718 286719 REPRESENTATION OF BYTES AND ITS ADDRESSES 286719 286718 286717 - - - 4 3 2 1 0 MEMORY ADDRESS C++ COMCEPTUAL MEMEORY MAP After the compilation of a program, C++ creates four logically distinct regions of memory for four distinct specific work. It is clear from the figure: GLOBAL VARIABLES STACK HEAP PROGRAM CODE This region holds return addresses at function call and arguments passed to functions while program is being executed. The stack also holds the current state of CPU. This region holds the free memory from which chunks of memory are allocated for dynamic memory allocation. This region is also known as Free Store which is unnamed and unutilized. This region holds the global variable of the program. Global variables remain in memory till the program continues. This region holds the compiled code of program. Each instruction & function of program starts at some certain address. C++ CONCEPTUAL MEMORY MAP MEMORY ALLOCATION Every data and instruction that are being executed are allocated some area in the main (internal) memory. This is done in two ways known as: (i) static memory allocation, and (ii) dynamic memory allocation STATIC MEMORY ALLOCATION When the memory allocation is known beforehand and is allocated at compile time, it is called static memory allocation. For example, when we declare variable as: short rate ; then for the variable rate 2 bytes is allocated at compilation time as short has 2 byte range. Thus it is static memory allocation. DYNAMIC MEMORY ALLOCATION When the memory is allocated as and when required during the program runtime, it is called dynamic memory allocation. The dynamic memory allocation is done with the help of two operators new and delete. Notes: 1 An object s life-time is (stay time in memory) is known as its extent. 2 Global variables or variables having file-scope are said to have static extent. 3 Variable having local scope are said to Page-1

~~~~~~~~~~~~~~~~~ have local extent. 4 Local variables with static specifier have static extent. 5 Objects, for which memory is dynamically allocated, have dynamic extent. DECLARATION AND INITIALIZATION OF POINTERS For declaring a pointer general syntax is: type *var_name ; Example: int *iptr ; char *cptr ; float *fptr ; Variable Address Meaning Let us try to understand the following code snippet: i 27 1050 i = 27, int *iptr int i = 27, j ; //declaration of int variable i. 1051 int *Iptr ; //declaration of int pointer. iptr 1050 1052 iptr = &i iptr = &i ;//iptr is pointing to mem. location of i. j 27 1053 j = i j = i ; Notes: 1 iptr = &i ; implies that iptr assigns address of i. 2 j = *iptr ; implies that j assigns the value at the address pointed by iptr. POINTER ARITHMETICS Only two arithmetic operation addition and subtraction may be performed on the pointers. Thus all pointers increase or decrease by the length of data type they point to. This is clear from the following example: char *cpt ; //note that char is of one byte int *iptr ; // note that int is of two byte [2] cptr ctpt+1 1001 1002 1003 1004 1005 1006 1007 1008 DYNAMIC ALLOCATION OPERATORS (new, delete) The operator new is used to create objects of all types including a class name. General form is: Pointer_variable = new data_type; Ex: iptr = new int; //allocates memory for int type. cptr = new char; // allocates memory for char type. fptr = new float; //allocates memory for float type. Once a pointer points to newly allocated memory, data values can be stored their using * operator, as is shown below: *cptr= a ; *fptr = 17.744; The new allocated memory can also be initialized at the time of allocation itself as shown below: char *cptr = new char( a ); float *fptr = new float(17.744); The operator new can also allocate memory for user-defined types like structures, arrays, and classes, as is shown below: Pointer_variable = new int[size] ; Ex: int *value = new int[17] ; It will create memory space from the free store for an array of 17 integers. Note: Array size must be supplied when new is used for array creation. Allocation of space for 2D array using new operator can be understood from the following program snippet: int *val; r,c; cout<< Enter dimensions (No. of row & column): ; cin>>r>>c; val = new int[r*c]; For reading the elements of this 2D-array we provide the code as shown below: for(int i=0; i<c; i++) { cout<< Enter elements in row <<(i+1)<< : ; for (int j=0; j<c; j++) { cin>>val[i*c+j]; //see here A[i][j] is replaced by A[i*c+j] iptr iptr+1 iptr+2 Address Page-2

~~~~~~~~~~~~~~~~~ The lifetime of an object created by new is not limited to the scope in which it is created. It lives in the memory until clearly deleted with the help of delete operator, so that memory may be freed for reuse. The general form for delete is: delete pointer_variable; Ex: delete ipter; delete[size] pointer variable Let us understand the working of new and delete operator by following program: [3] Program: Program to create two array to store roll numbers and marks of some students, whose number would be known at run time(illustration of free store operation.) #include<iostreatm.h> int *rollno; //declaration of int pointer for rollno array float *marks; //declaration of float pointer for marks array { int size; cout<< How many element are there in the array?:\ ; cin>>size; rollno = new int[size]; //dynamic allocation of rollno array marks = mew float[size];//dynamic allocation of marks array //Checking of availability of memory. if((!rollno) (!marks)) //if rollno or marks is null pointer { cout<< Out of Memory! Aborting! ; return 1; //Read in values in the array elements for (int i=0; i<size; i++) { cout<<enter rollno and marks for student <<(i+1)<< \n ; cin>>rollno[i]>>marks[i]; //Display the array contents cout<< \troll no\tmarks\n ; for(i=0; i<size; i++) cout<< t <<rollno[i] << t\t <<marks[i]<< \n ; delete[ ]rollno; delete[ ]marks; ORPHNED MEMORY BLOCK AND MEMORY LEAK A block of memory dynamically allocated with the help of new operator and nit deallocated with the help of delete operator is called orphaned memory block. A program containing orphaned memory block xonsumes some amout of memory, every time the program is executed/run, which causes adverse effect on the system. This situation is called memory leak. POSSIBLE CAUSES/REASONS OF MEMORY LEAK 1 Improper use of new and delete operator. 2 Forgetting to delete something dynamically allocted. 3 Bypassing the delete statement by programmer. 4 Assigning the result of a new statement to a pointer which already points to an allocated object. POINTERS AND ARRAY and arrays are closely related in C++. The name of an array is a pointer pointing to the first element of the array. The array-name gives the base address of the array. Naturally arr-name+1 will give the address of second element, arry-name +2 will give the address of third element, and so on. Thus, to print the fourth element of array age we can use either of the following: cout <<age[3]; cout <<*(age+3); Page-3

[4] ~~~~~~~~~~~~~~~~~ Note that: *(age+3) Value at the address of (age+3) Value at the (address of age +3) Value at the address of (1001 +3) Value at the address of 1004 25. ARRAY OF POINTERS The syntax for the declaration of array of pointers is: Data_type *pointer_name[size]; Ex: float *fp[7];// array of 7 float pointers This declaration means - ip is an array of 7 elements and each element is a points to a elements and each element is a pointer to a variable of float type. Let us understand this by following program: PROGRAM Illustration of concept of array of pointers. # { int *ip[4] //initialization of array pointers pointing to 4 integer values. int fe = 16, fi = 25, fo = 34, fum = 43; ip[0]=&fe; ip[1]=&fi; ip[2]=&fo; ip[3]=&fum; //Display of values pointed by pointers for(i=0; i<4; i++) { cout<< The pointer ip[ <<i<< ] points to <<*ip[i]<< \n ; //Display fo addresses stored in the array cout<< The base address of array ip is <<ip<< \n ; for(i=0; i<4; i++) { cout<< Address of ip[ <<i<< ]is <<ip[i]<< \n ; FORMULAE FOR THE SOULTION TO THE ARRAY OF POINTERS value address age[6] 60 1007 age[5] age[4 age[3] age[2] age[1] age[0] 40 32 25 33 28 26 1006 1005 1004 1003 1002 1001 1 *A = *(A) = *(A + 0) = A[0] **A = *(*(A = 0)) = *(A[0] + 0) *(A + 1) = A[1] 2 *(*A + 1) = *(A[0] + 1) = A[0][1] *(A + i) = A[i] *(*(A + i) + j) = *(A[i] + j) = A[i][j] Let us understand the use of pointer arithmetic with the help of following pgroam: Program-1 : for the manipulation of 2-d array #inclued<iostream.h> { int x[3][5] = {{1, 2, 3, 4, 5, {6, 7, 8, 9, 10, {11, 12, 13, 14, 15 ; int *n = &x[0][0]; cout<< (1) *(*(x + 2) + 1) \t = << *(*(x + 2) + 1) <<endl ; cout<< (2) *(*x + 2)+ 5 \t = << *(*x + 2) + 5 <<endl ; cout<< (3) *(*(x + 1)) \t = << *(*(x + 1) ) <<endl ; cout<< (4) *(*(x) + 2) + 1 \t = << *(*(x) + 2) + 1) <<endl ; cout<< (5) *(*(x + 1) + 3) \t = << *(*(x + 1) + 3) <<endl ; cout<< (6) *n \t \t = << *n <<endl ; cout<< (7) *(n + 2) \t = << *(n + 2) <<endl ; cout<< (8) (*(n + 3) + 1) \t = << (*(n + 3) + 1) <<endl ; cout<< (9) *(n + 5) + 1 \t = << *(n + 5) + 1 <<endl ; Page-4

[5] ~~~~~~~~~~~~~~~~~ cout<< (10) ++*n \t = << ++*n <<endl ; [OUPTPUT HINT : 12, 8, 6, 4, 9, 1, 3, 5, 7, 2] Program-2 : for the manipulation of ARRAY OF POINTERS #inclued<iostream.h> { int x[3][5] = {{18, 20, 13, 24, 35, {7, 8, 6, 19, 10, {19, 22, 30, 21, 15 ; int *n = &x[0][0]; cout<< (1) (*(n + 3) + 1) \t = << (*(n + 3) + 1) <<endl ; cout<< (2) *(n + 2)+ 5 \t = << *(n + 2) + 5 <<endl ; cout<< (3) *(*x + 2) + 5 \t = << *(*x + 2) + 5 <<endl ; cout<< (4) ++*n \t = << ++*n <<endl ; cout<< (5) *(*(x) + 2) + 1 \t = << *(*(x) + 2) + 1 <<endl ; cout<< (6) *n \t \t = << *n <<endl ; cout<< (7) *(*(x + 2) +1) \t = << *(*(x + 2) +1) <<endl ; cout<< (8) *(*(x + 1) +3) \t = << *(*(x + 1) +3) <<endl ; cout<< (9) *(*(x + 1)) \t = << *(*(x + 1)) <<endl ; cout<< (10) *(n + 5) +1 << *(n + 5) +1 <<endl ; [OUPTPUT HINT : 35, 13, 15, 19, 14, 18, 22, 19, 7, 8] POINTERS And STRINGS We know that group of character of any length is known as string, last character being a null character(\0). A pointer can point to a string by following declaration: char name[ ]= Self-Help ; char *cp; // declaring a character pointer for (cp=name; *cp!= \0 ; cp++) cout<<*cp; Ex: What would be the output of following: #include<iostream.h> { char *ptr; ptr = nice ; cout<<++*ptr; Notes: Several strings can be stored as: char *neme[ ]={ chair, table, desk ; POINTER AND FUNCTIONS INVOKING FUNCTION BY PASSING THE REFERENCE Program : To swap values of two variables #include<iostream.h> { void swap(int&, int&); //FP int a=7, b=4; cout<< Original value of a= <<a<< and b= <<b<<endl; swap(a,b);//fc by reference cout<< Swapped value of a= <<a << and b= <<b<<endl; void swap(int &x, int &y) //FD { int temp; temp = x ; x = y; y = temp; Page-5

~~~~~~~~~~~~~~~~~ INVOKING FUNCTION BY PASSING THE POINTER Program : To swap values of two variable by passing pointer #include<iostream.h> { void swap(int *x, int*y); //FP int a=7, b=4; cout<< Original value of a= <<a<< and b= <<b<<endl; swap(&a, &b); cout<< Swapped value of a= << a << and b = << b << endl ; void swap(int *x, int *y) //FD { int temp; temp = *x ; *x = *y; *y = temp; [6] FUNCTION RETURNING POINTERS PROGRAM : TO ILLUSTRATE A FUNCTION RETURNING A POINTER. # include <iostream.h> int *big (int&, int&) ;//function prototype of a function returning a pointer void main ( ) { int a, b, *c ; cont<< enter two integers : << endl ; cin >>a, b ; c = big(a, b) ; //function call cout<< The bigger value is << *c <<endl ; //note that in FC we calculated the // value of c but display is given by *c int *big(int &x, int &y) //function def. of a function returning a pointer { if(x >y) return (&x) ; else return (&y) ; OUTPUT : Enter two integers 7 13 The bigger value is 13 STRUCTURE POINTER The pointer to a structure is called structure pointer. General form of declaration of structure pointer is: sturct-name *sturct-pointer; Ex: sturct date{short int dd, mm, yy ; ; date *dptr; // dptr = date-pointer OR struct date{short int dd, mm, yy ; *dptr; // sturct-type & sturct pointer is combined. Using structure pointer, the memory of structures are accessed by using arrow operator (->) as, dptr ->dd; dptr ->mm; dptr ->yy; Program : To illustrate the use of structure-pointer. #include<iostream.h> { sturct date{dhort int dd, mm, yy ; join-date = {10,09,07 ; date *dptr; dptr=&join-date; cout<< Display of structure elements using structure variable: ; cout<< join-date.dd<< - << join-date.mm << - << join-date.yy ; cout<< Display of structure elements using structure pointer\n ; cout<<dptr->dd<< - <<dptr->mm << - <<dptr->yy<<endl; There are two primary uses of structure pointers: (i) to generate a call by reference to a function (ii) to create dynamic data structure such as linked list, stacks, queues, trees etc. Page-6

[7] ~~~~~~~~~~~~~~~~~ SELF-REFERENTIAL STRUCTURE A structure having a member element referring to the structure itself is called self-referential structure. It is clear from the following figure: DYANAMIC STURCTURE The structure for which memory is allocated dynamically is called synamic structure. The new operator is used for creating dyanamic sturctue, as is given below: Struct-pointer=new struct-type; Ex: contest *cptr;//candidate pointer cptr= new contest; A dynamic structure must be deallocated after its use is over. It can be done as; delete cptr; OBJECT POINTER A pointer pointing to object called object pointer. It declared as: class-name *object-pointer; Ex: class something{ int a,b; public:..;; {something s1;//declaring an object something *ps1;//declaring object pointer.. THIS POINTER This pointer is an special pointer which stores the address of the object that is currently invoking(executing) a member function of a class. Program : To display the address of object using this pointer #include<iostream.h> class sample{ private: int x; public: void display( );; void sample::display( ) { cout<< Object s address = <<this<<endl; { sample obj1, obj2, obj3; obj1.display( ); obj2.display( ); obj3.display( ); OUTPUT: Object s address = ox24e0fff2 Object s address = ox24e0fff0 Object s address = ox24e0ffee Demonstration : Of how the this pointer is used to access the member data of a class. #include<iostream.h> class sample{ private: int x; public: void display( ) ; ; void sample::display( ) { this ->x = 20; cout<< Content of x = <<this->x<<endl; { sample obj1; obj1.display( ); [OUTPUT: Content of x = 20] HOME-WORK Problem: 4, 8, 12, 20, 24 and Find the output of following program: #include<iostream.h> { int x[3][5]={{18,20,13,24,35, {7,8,6,19,10, {19,22,30,21,15 int *n=&x[0][0]; cout<< (1)\t <<(*(n+3)+1)<<endl; cout<< (2)\t <<*(n+2)<<endl; cout<< (3)\t <<*(*x+2)+5<<endl; cout<< (4)\t <<++*n<<endl; cout<< (5)\t <<*(*(x)+2)+1<<endl; cout<< (6)\t <<*n<<endl; cout<< (7)\t <<(*(x+2)+1)<<endl; cout<< (8)\t <<(*(x+1)+3)<<endl; cout<< (9)\t <<(*(x+1))<<endl; cout<< (10)\t <<*(n+5)+1<<endl; Page-7