Вы находитесь на странице: 1из 47

Pointers

Problem solving using C++

Pointer is a memory location or a variable which stores the memory address of another variable in memory. Pointers are much more commonly used in C++ (and C) than in many other languages (such as BASIC, Pascal, and certainly Java, which has no pointers).
Problem solving using C++

What are pointers for? Here are some common uses: Accessing array elements Passing arguments to a function when the function needs to modify the original argument Passing arrays and strings to functions Obtaining memory from the system Creating data structures such as linked lists, binary trees etc.
Problem solving using C++

Reasons for using pointers


It enables us to access a variable that is defined outside the function. More efficient in handling the data tables. Pointers reduce the length and complexity of a program They increase the execution speed The use of a pointer array to character strings results in saving of data storage space in memory.
Problem solving using C++

Consider the following statement int quantity =50; This statement instructs the system to find a location for the integer variable quantity and puts the value 50 in that location. Let us assume that system has chosen address location 5000 for quantity. We may represent this as shown in the following figure.

Problem solving using C++

During Execution of the program, the system always associates the name quantity with the address 5000. We may have access to the value 50 by using either the name of the variable quantity or the address 5000. Since memory addresses are simply numbers, they can be assigned to some variables which can be stored in memory, like any other variable.

Problem solving using C++

Accessing the address of a variable


The statement p= &quantity ; would assign the address 5000 (the location of quantity) to a variable p.

Problem solving using C++

The operator & can be called as address of and can be used only with a simple variable or an array element. The following statements are not valid. 1. &50 (pointing at constant) 2. int x[10]; &x (pointing at array name) 3. &(x+y) (pointing at expressions). Note: If x is an array , then expressions such as &x[0] and &x[i+3] are valid and represent the addresses of 0th and (i+3) th elements of x.
Problem solving using C++

The ideas behind pointers are not complicated. Heres the first key concept: Every byte in the computers memory has an address. Addresses are numbers, just as they are for houses on a street. The numbers start at 0 and go up from there1, 2, 3, and so on. The Address-of Operator & You can find the address occupied by a variable by using the address-of operator &. Heres a short program, that demonstrates how to do this:
Problem solving using C++

# include <iostream.h> void main() { int var1 = 11; //define and initialize int var2 = 22; //three variables int var3 = 33; cout << &var1 << endl //print the addresses << &var2 << endl //of these variables << &var3 << endl; } Note :Remember that the address of a variable is not at all the same as its contents. The contents of the three variables are 11, 22, and 33 .
Problem solving using C++

The above simple program defines three integer variables and initializes them to the values 11, 22, and 33. It then prints out the addresses of these variables. The actual addresses occupied by the variables in a program depend on many factors, such as the computer the program is running on, the size of the operating system, and whether any other programs are currently in memory. For these reasons you probably wont get the same addresses when you run this program
Problem solving using C++

Declaring and initializing pointers


Syntax Data type * pt_name; This tells the compiler 3 things about the pt_name. 1. The asterisk(*) tells the variable pt_name is a pointer vaiable. 2. pt_name needs a memory location. 3. pt_name points to a variable of type Data type
Problem solving using C++

For example int *p; declares the variable p as a pointer variable that points to an integer data type.

float *x; declares x as a pointer to floating point variable. Once a pointer variable has been declared, it can be made to point to a variable using an assignment statement such as p=&quantity; i.e p now contains the address of quantity. This is known as pointer initialization.
Problem solving using C++

1. Before a pointer is initialized, it should not be used. 2. We must ensure that the pointer variables always point to the corresponding type of data. 3. Assigning an absolute address to a pointer variable is prohibited. i. e, p=5000; A pointer variable can be initialized in its declaration itself. For example, int x, *p=&x; It declares x as an integer variable and then initializes p to the address of x.
Problem solving using C++

The statement int *p = & x, x; is not valid. i. e, target variable x must be declared first. Accessing a variable through its pointer A variable can be accessed by using unary operator *(asterisk) known as indirection operator. Consider the following statements:

Problem solving using C++

int quantity, *p, n; quantity =50; p=&quantity; n=*p; The first line declares quantity and n as integer variables p is a pointer pointing to an integer. The second line assigns the value 50 to quantity and the third line assigns the address of quantity to the pointer variable p. The fourth line contains the indirection operator *.

Problem solving using C++

When the operator * is placed before a pointer variable in an expression on the R.H.S of equal sign, the pointer returns the value of the variable quantity, because p is the address of quantity. The * can be remembered as value at address. The value of n would be 50. The two statements p =&quantity; n =*p; are equivalent to n =*&quantity; which in turn equal to n = quantity;
Problem solving using C++

//Accessing the variable pointed to void main() { int var1 = 11; //two integer variables int var2 = 22; int *ptr; //pointer to integers ptr = &var1; //pointer points to var1 cout << *ptr << endl; //print contents of pointer (11) ptr = &var2; //pointer points to var2 cout << *ptr << endl; //print contents of pointer (22) } This program prints the integer value stored at the address thats stored in ptr. Heres the output: 11 22
Problem solving using C++

/Accessing via pointers. void main() { int var1, var2; //two integer variables int* ptr; //pointer to integers ptr = &var1; //set pointer to address of var1 *ptr = 37; //same as var1=37 var2 = *ptr; //same as var2=var1 cout << var2 << endl; //verify var2 is 37 }
Problem solving using C++

int* ptr; //declaration: pointer to int *ptr = 37; //indirection: value of variable pointed to by ptr . Using the indirection operator to access the value stored in an address is called indirect addressing, or sometimes dereferencing, the pointer.

Problem solving using C++

Heres a summary of what weve learned so far: int v; //defines variable v of type int int* p; //defines p as a pointer to int p = &v; //assigns address of variable v to pointer p v = 3; //assigns 3 to v *p = 3; //also assigns 3 to v

Problem solving using C++

Difference between the reference and dereference operators


& is the reference operator and can be read as "address of" * is the dereference operator and can be read as "value pointed by"

Problem solving using C++

Another example: pointers


#include <iostream.h> void main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed by p1 = 10 *p2 = *p1; // value pointed by p2 = value pointed by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; }
Problem solving using C++

Pointer expressions
Pointer variables can be used in expressions. For Example, if p1 and p2 are properly declared and initialized pointers, then following statements are valid. y= *p1* *p2 ; same as (*p1) * (*p2) sum=sum+ *p1; z=5 * - *p2 / *p1; same as ( 5 * ((*p2)))/(*p1) There is a blank space between / and * . *p2 =*p2 +10; solving using C++ Problem

Addition of integers p1+4 Subtraction of integers from pointers. p2 - 2 Subtraction of one pointer from another p1-p2

Problem solving using C++

Short hand operators may also be used with the pointers. p1++; --p2; Sum+=*p2; are valid statements. Pointers can also be used to compare things using relational operators. p1>p2. p1==p2 p1!=p2 are valid statements.
Problem solving using C++

Pointers are not used in division and multiplication. p1/p2; p1*p2; p1/3; are not allowed. Two pointers can not be added. p1+p2 is illegal.

Problem solving using C++

Write a c++ program to illustrate the use of pointers in arithmetic operations.

#include<iostream.h> void main() { int a, b, *p1, *p2, x,y,z; a=12; b=4; p1=&a; p2=&b; x= *p1 * *p2 6; y=4* - *p2/ *p1 +10; cout<<a=<<a<<endl<< b=<<b<<endl<< x=<<x<<endl<< y=<<y<<endl;

Problem solving using C++

*p2 = *p2 +3; *p1 = *p2 -5; z= *p1 * *p2 - 6; cout<<a<<\t<<b<<\t<<z; } output: a=12 b=4 x=42 y=9 2 7 8
Problem solving using C++

When we increment a pointer , its value is increased by the length of the data type that it points to. This length is called the scale factor. For example, p1++; where p1 is a pointer pointing to some integer variable with an initial value, say 2800, then after p1 =p1+1, the value of p1 will be 2802 (assuming that an integer in memory occupies 2 bytes)
Problem solving using C++

Pointers and arrays


When an array is declared, the compiler allocates a base address and sufficient amount of storage to contain all the elements of the array in contiguous memory locations The base address is the location of the first element (index 0) of the array. The compiler also defines the array name as a constant pointer to the first element.
Problem solving using C++

Suppose we declare an array x as follows int x[5] ={ 1,2,3,4,5}; Suppose the base address of x is 1000 and assuming that each integer requires 2 bytes, the five elements will be stored as follows.

Problem solving using C++

The name x is defined as a constant pointer pointing to the first element, x[0] and therefore the value of x is 1000, the location where x[0] is stored. That is x =&x[0] =1000 If we declare p as an integer pointer, then we can make the pointer p to the array x by the following statement. p=x; This is equivalent to p=&x[0]; Now we can access every value of x using p++ to move from one element to another. The relationship between p and x is shown below.
Problem solving using C++

p= &x[0] (=1000) p+1=&x[1] (=1002) p+2=&x[2] (=1004) p+3=&x[3] (=1006) p+4=&x[4] (=1008) Address of x[3] = base address + (3 x scale factor of integer) =1000 +(3*2) =1006

Problem solving using C++

We can also use pointers to access array elements . This method i. e, pointer accessing method is much faster than array indexing. *(p+3) gives the value of x[3]. Note: If p1 and p2 are both pointers to same array, then p2-p1 gives the number of elements between p1 and p2. For eg; if p1= &a[0] and p2 =&a[5] then p2-p1 = 5
Problem solving using C++

void main() { int intarray[5] = { 31, 54, 77, 52, 93 }; for(int j=0; j<5; j++) //for each element, cout << intarray[j] << endl; //print value; } The cout statement prints each array element in turn. For instance, when j is 3, the expression intarray[j] takes on the value intarray[3] and accesses the fourth array element, the integer 52. Heres the output 31 54 77 52 93
Problem solving using C++

#include <iostream.h> void main( ) { //array int intarray[5] = { 31, 54, 77, 52, 93 }; for(int j=0; j<5; j++) //for each element, cout << *(intarray+j) << endl; //print value }

Problem solving using C++

// array accessed with pointer #include <iostream.h> void main() { int intarray[] = { 31, 54, 77, 52, 93 }; //array int* ptrint; //pointer to int ptrint = intarray; //points to intarray for(int j=0; j<5; j++) //for each element, cout << *(ptrint++) << endl; //print value }
Problem solving using C++

Write a c++ program to compute the sum of all elements stored in an array. void main() { int *p, sum, j; int x[5] ={5, 9, 6,3,7}; int i=0; p=x; // or p=&x[0]; sum=0; while(i<5) { cout<<x[<<i<<]<<=<<\t<<*p<<\t<<p<<endl; sum+=*p; i++; p++; } cout<<sum =<<sum<<endl; }
Problem solving using C++

Write a c++ program to exchange two values # include<iostream.h> void main() { int x, y, t,*a,*b; a=&x; b=&y; cin>>*a>>*b;// equivalent to cin>>x>>y; t=*a; *a=*b; *b=t; cout<<x=<<x<<endl; cout<<y=<<y<<endl; }
Problem solving using C++

#include <iostream.h> void main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; }
Problem solving using C++

Pointers and character strings


The statement char *cptr =name; declares cptr as a pointer to a character and assigns address of the first character of name as the initial value. The statement while(*cptr!=\0) is true until the end of the string is reached. When the while loop is terminated, the pointer cptr holds the address of the null character. The statement length = cptr name; gives the length of the string name.
Problem solving using C++

A constant character string always represents a pointer to that string. The following statements are valid. char *name; name =Delhi; These statements will declare name as a pointer to character and assign to name the constant character string Delhi Handling table of strings: For example,
Problem solving using C++

char name[3][25]; This says that the name is a table containing 3 names , each with a maximum length of 25 characters (including null character) The total storage requirements for the name table are 75 bytes We know that rarely the individual strings will be of equal lengths. Therefore, instead of making each row a fixed number of characters, we can make it a pointer to a string of varying length.
Problem solving using C++

For example, char *name[3] = { New Zealand , Australia, India}; Declares name to be an array of 3 pointers to characters, each pointer pointing to a particular name as shown below. name[0] New Zealand name[1] Australia name[2] India This declaration allocates 28 bytes.
Problem solving using C++

The following statement would print out all the 3 names. for(i=0; i<=2;i++) cout<<name[i];
To access the jth character in the ith name, we may write as *(name[i] +j) The character array with rows of varying lengths are called ragged arrays and are better handled by pointers.
Problem solving using C++

Note: [] has higher precedence than * , *p[3] declares p is an array of 3 pointers (*p)[3]declares p as a pointer to an array of three elements. //length of the string void main() { char name[]="Manipal Institute of Technology"; char *cptr=name; while(*cptr!='\0') cptr++; cout<<"length="<<cptr-name; }
Problem solving using C++

Вам также может понравиться