Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointers Ritika sharma.

Similar presentations


Presentation on theme: "Pointers Ritika sharma."— Presentation transcript:

1 Pointers Ritika sharma

2 Variable A variable is a named memory location.
Variables provide direct access to its memory location. A variable has a name, an address, a type,and a value: "the name identifies the variable to the programmer "the address specifies where in main memory the variable is located Ritika sharma

3 What is a variable? "the type specifies how to interpret the data stored in main memory and how long the variable is "the value is the actual data stored in the variable after if has been interpreted according to a given type Ritika sharma

4 Pointer variable A pointer is a variable that contains the memory location of another variable. Syntax:- type * variable name  You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. Ritika sharma

5 Declaring a Pointer Variable
To declare ptr as an integer pointer: int *ptr; To declare ptr as a character pointer: char *ptr; Ritika sharma

6 Accessing a variable through its pointer
Once we declare a pointer variable we must point it to something. We can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=# This places the address where num is stores into the variable ptr. If num is stored in memory address then the variable ptr has the value Ritika sharma

7 Engineering H192 Winter 2005 Address and Pointers Memory can be conceptualized as a linear set of data locations. Variables reference the contents of a locations Pointers have a value of the address of a given location ADDR1 Contents1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6 * * * Instructor: A computer has two basic types of busses to the memory: an address and data bus. Thus far we have been concerned mainly with the data we store but not its storage location. Pointers allow us to also use the address in which our data is stored in various ways. This conceptualization of memory can be likened to a street with various address where mail is delivered. The mailman delivers the correct data (letters) to the correct address written on each piece of mail. ADDR11 Contents11 * * ADDR16 Contents16 Ritika sharma Lecture 14

8 Assume ptr is a pointer variable and x is an integer variable
10 ptr &x Now ptr can access the value of x. HOW!!!! Write: *variable . For example: Cout<< *ptr; x = 10 ptr = &x Ritika sharma

9 Variables, Addresses and Pointers
main() { int a = 5; int b = 6; int *c; // c points to a c = &a; } Memory Value a (1001) b (1003) 6 c (1005) 1001 Ritika sharma

10 Pointers of different datatypes assigned to different variables
include< stdio.h >  {  int num, *intptr;  float x, *floptr;  char ch, *cptr;  num=123;  x=12.34;  ch=’a’;  intptr=&num;  cptr=&ch;  floptr=&x;  cout<<“Num “<<*intptr,<<“ stored at address “<<intptr;  cout<<“Value “<<*floptr <<“ stored at address “<<floptr;  cout<<“Character <<*cptr <<“stored at address”<<cptr;  } Ritika sharma

11 Run this code int main() { int x; int *ptr; x = 10; ptr = &x; *ptr = *ptr + 1; cout<< x; return 0; } Ritika sharma

12 Pointer Arithmetic Valid operations on pointers include:
- the sum of a pointer and an integer - the difference of a pointer and an integer - pointer comparison the difference of two pointers. Increment/decrement in pointers assignment operator used in pointers Ritika sharma

13 Example void main() { int a=25,b=78,sum; int *x,*y; x=&a; y=&b;
sum= *x + *y; cout<<“Sum is : ”<<sum; } Ritika sharma

14 Assignment in pointers
Pointer variables can be "assigned": int *p1, *p2; p2 = p1; Assigns one pointer to another "Make p2 point to where p1 points" Do not confuse with: *p1 = *p2; Assigns "value pointed to" by p1, to "value pointed to" by p2 Ritika sharma

15 Diagrammatic representation
Ritika sharma

16 Comparison in pointers
Two pointers of the same type, p and q, may be compared as long as both of them point to objects within a single memory block • Pointers may be compared using the <, >, <=, >=, == , != • When you are comparing two pointers, you are comparing the values of those pointers rather than the contents of memory locations pointed to by these pointers Ritika sharma

17 Increment and decrement
Data Type Initial address Operation Address after operation s Required bytes Int i=2 4046 ++ -- 4048 4044 2bytes Char c=‘x’ 4053 4054 4042 1bytes Float f=2.2 4050 4bytes Long l=2 4060 4064 4056 Ritika sharma

18 Increment and decrement Addition and subtraction Comparison Assignment
You can perform a limited number of arithmetic operations on pointers. These operations are: Increment and decrement Addition and subtraction Comparison Assignment The increment (++) operator increases the value of a pointer by the size of the data object the pointer refers to. For example, if the pointer refers to the second element in an array, the ++ makes the pointer refer to the third element in the array. The decrement (--) operator decreases the value of a pointer by the size of the data object the pointer refers to. For example, if the pointer refers to the second element in an array, the -- makes the pointer refer to the first element in the array. Ritika sharma

19 You can add an integer to a pointer but you cannot add a pointer to a pointer.
If the pointer p points to the first element in an array, the following expression causes the pointer to point to the third element in the same array: p = p + 2; If you have two pointers that point to the same array, you can subtract one pointer from the other. This operation yields the number of elements in the array that separate the two addresses that the pointers refer to. You can compare two pointers with the following operators: ==, !=, <, >, <=, and >=. Pointer comparisons are defined only when the pointers point to elements of the same array. Pointer comparisons using the == and != operators can be performed even when the pointers point to elements of different arrays. You can assign to a pointer the address of a data object, the value of another compatible pointer or the NULL pointer. Ritika sharma

20 Void pointers When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to typecast it to another kind of pointer first. Hence the term Generic pointer. Ritika sharma

21 This is very useful when you want a pointer to point to data of different types at different times.
Syntax: void * variable name; Ritika sharma

22 Void pointer Is a pointer that can hold the address of variables of different data types at different times also called generic pointer. The syntax for declaring a void pointer is void *pointer_name; Here, the keyword void represents that the pointer can point to value of any data type. But before accessing the value through generic pointer by dereferencing it, it must be properly typecasted. To Print value stored in pointer variable: *(data_type*) pointer_name; Ritika sharma

23 Limitations of Void pointers:
1.Void pointers cannot be directly dereferences. They need to be appropriately typecasted. 2.Pointer arithmetic cannot be performed on void pointers. Ritika sharma

24 void main() { int i; char c; void
void main() { int i; char c; void *data; i = 6; c = 'a'; data = &i; cout<<"the_data points to the integer value “<< *(int*) data; data = &c; cout<<"the_data now points to the character “<< *(char*) data; } Ritika sharma

25 PROBLEMS WITH POINTER Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. Ritika sharma

26 DANGLING POINTER Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory As the system may reallocate the previously freed memory to another process, if the original program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. Ritika sharma

27 Cause: deleting an object from memory explicitly or by destroying the stack frame on return does not alter associated pointers. The pointer still points to the same location in memory even though the reference has since been deleted and may now be used for other purposes Ritika sharma

28 NULL POINTER To overcome the problem of Dangling or Wild pointer, we use NULL pointer. A NULL value will be assigned after deleting the object or the pointer. A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type- casting the integer value zero to any pointer type. int * p; p = 0; // p has a null pointer value Ritika sharma

29 Do not confuse null pointers with void pointers
Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to. Ritika sharma

30 WILD POINTER Wild pointers arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same erratic behaviour as dangling pointers, though they are less likely to stay undetected. The wild pointer generates garbage memory location and pendent refernce. Ritika sharma

31 Example of wild pointer: int *ptr;
Pointer which are not initialized during its definition holding some junk value( a valid address) are Wild pointer. Example of wild pointer: int *ptr; Every pointer when it is not initialized is defined as a wild pointer. As pointer get initialized, start pointing to some variable its defined as pointer, not a wild one. Ritika sharma

32 Causes: Pointer declared but not initialized Pointer alteration
Accessing destroyed data Ritika sharma

33 Pointers to pointers int main() { int a=2, *p, **q; p=&a; q=&p;
A pointer variable containing address of another pointer variable is called pointer to pointer int main() { int a=2, *p, **q; p=&a; q=&p; cout<<a<<“is stored at ”<<p<<“and pointer is stored at ”<<q; return 0; } Ritika sharma

34 Dynamic Memory Allocation
NEW= To allocate the memory dynamically. It is similar to malloc () function used in C language. DELETE= To delete the allocated memory dynamically. It is similar to free () function used in C language. Synatx:- float *p; p=new float; Ritika sharma

35 Contd…. char *p; p=new char; Struct student { int rollno; char name[20]; } *ptr; ptr=new student; TO DELETE:- ptr=new int; or ptr=new int[20]; Delete ptr; delete[]ptr; Ritika sharma

36 Question…. A program to demonstrate how pointer to a function is declared to perform simple arithmetic operation such as add, sub, mul, div of two numbers. Ritika sharma

37 Pointer and Array An array itself act as pointer, as one element in an array is stored adjecent to the previous OR The concept of array is very much bound to the one of pointer. In fact, the identifier of an array is equivalent to the address of its first element, as a pointer is equivalent to the address of the first element that it points to, so in fact they are the same concept. Ritika sharma

38 Contd… For example, int numbers [20]; int * p;
The following assignment operation would be valid:  p = numbers; Or P=&numbers[0]; Ritika sharma

39 Contd… After that, p and numbers would be equivalent and would have the same properties. The only difference is that we could change the value of pointer p by another one, whereas numbers will always point to the first of the 20 elements of type int with which it was defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an array can be considered as constant pointer. Ritika sharma

40 Pointer and Array int main() { int *ptr1, i, a[5]={10,20,30,40,50}; i=0; ptr1=&a[0]; while(i<=5) cout<<“address=“<<ptr1; cout<<“elements=“<<*ptr1; i++; ptr1++; } return 0; Ritika sharma

41 Questions!! Program to calculate average of array elements using pointer. Program to find maximum element from array using pointer. Ritika sharma

42 Pointer to Object Pointers can point to simple data types and the objects also. Eg:- distance *distptr; Where dist is the object of the distance class. To access the values:- (*distptr).getdata(); // we use paranthesis because dot opertaor has higher precedence than * (dereference operator). Or distptr->getdata(); Ritika sharma

43 distptr->getdist(); distptr->showdist(); cout << endl;
#include <iostream> using namespace std; class Distance { private: int feet; float inches; public: void getdist() cout << "\nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } void showdist() cout << feet << " feet " << inches << "inches \n"; }; int main() { Distance dist; dist.getdist(); dist.showdist(); Distance* distptr; distptr=&dist; distptr->getdist(); distptr->showdist(); cout << endl; return 0; } Ritika sharma

44 This pointer Each object maintains a pointer to itself which is called the “this” pointer. Each object can determine it’s own address by using the “this” keyword. Many member functions of a class in C++ require no arguments because of the use of the implicit pointer “this”. Ritika sharma

45 int main() { myclass ob; ob.getdata(); ob.print1(); ob.print2();
return 0; } class myclass { int data; public: void getdata() data=100; } void print1() cout<<data<<endl; void print2() cout<<this<<endl; cout<<this->data; }; Ritika sharma

46 OUTPUT 100 0x6ffe40 Ritika sharma

47 class student { int rollno; float marks; public: void getdata(int x,float y) rollno=x; marks=y; } student greater(student ob) if(ob.marks>=marks) return ob; else return *this; void display() cout<<rollno<<" "<<marks; }; Ritika sharma

48 pointer to data member class data { public: int a; void print() cout<<"a="<<a; } }; int data::*ptr; ptr=&data::a; ob.*ptr=23; void data::*p(); p=&data::print; (ob.*p)(); Ritika sharma

49 Pointers in class class book { int *price; int *year; public:
void getdata(int x, int y); void putdata() cout<<*price<<*year; } }; void book::getdata(int x, int y) price=&x; year=&y; Ritika sharma


Download ppt "Pointers Ritika sharma."

Similar presentations


Ads by Google