Chapter 13

Pointers

CHAPTER OUTLINE
13.1  INTRODUCTION

Many learners feel that pointers is a puzzling topic. However, pointers can make programs quicker, straightforward, and memory efficient. C/C++ gives more importance to pointers. Hence, it is important to know the operation and applications of pointers. Pointers are used as tools in C/C++ and if you fail to understand them, you will lose the power of C/C++.

Similar to C, in C++, variables are used to hold data values during program execution. When declared, every variable occupies certain memory locations. It is possible to access and display the address of the memory location of a variable using ‘&’ operator. Memory is arranged in series of bytes. These series of bytes are numbered from zero onward. The number specified to a cell is known as memory address. A pointer variable stores the memory address of any type of variable. The pointer variable and normal variable should be of the same type. The pointer is denoted by (*) asterisk symbol.

A byte is nothing but a combination of eight bits, as shown in Figure 13.1. The binary numbers 0 and 1 are known as bits. Each byte in the memory is specified with a unique (matchless) memory address. The memory address is an unsigned integer starting from zero to uppermost addressing capacity of the microprocessor. The number of memory locations pointed by a pointer depends on the type of the pointer. The programmer should not worry about the addressing procedure of the variables. The compiler takes care of this. The pointers are either 16 bits or 32 bits long.

Fig. 13.1

Fig. 13.1 Memory representation

The allocation of memory during program run time is called dynamic memory allocation. Such a type of memory allocation is essential for data structure, and it is efficiently handled by pointers. Arrays are another reason for using pointers. Arrays are used to store more values. Actually, the name of the array is a pointer. Command-line arguments are one more reason for using pointers. These arguments are passed to programs and are stored in an array of pointers argv [].

 

POINTERS

A pointer is a memory variable that stores a memory address. Pointers can have any name that is legal for other variables, and it is declared in the same fashion as other variables, but it is always denoted by ‘*’ operator.

13.2  FEATURES OF POINTERS
  1. Pointers save memory space.
  2. Execution time with pointers is faster, because data are manipulated with the address, that is, direct access to memory location.
  3. Memory is accessed efficiently with the pointers. The pointer assigns as well as releases the memory space. Memory is dynamically allocated.
  4. Pointers are used with data structures. They are useful for representing two-dimensional and multi-dimensional arrays.
  5. We can access the elements of any type of array, irrespective of its subscript range.
  6. Pointers are used for file handling.
  7. Pointers are used to allocate memory in a dynamic manner.
  8. In C++, a pointer declared to a base class could access the object of a derived class. However, a pointer to a derived class cannot access the object of a base class. The compiler will generate an error message “cannot convert ‘A* to B*,’” where A is the base class and B is the derived class.
13.3  POINTER DECLARATION

Pointer variables can be declared as follows:

 

Example

int *x;

float *f;

char *y;

  1. In the first statement, ‘x’ is an integer pointer, and it informs the compiler that it holds the address of any integer variable. In the same way, ‘f’ is a float pointer that stores the address of any float variable, and ‘y’ is a character pointer which stores the address of any character variable.
  2. The indirection operator (*) is also called the dereference operator. When a pointer is dereferenced, the value at that address stored by the pointer is retrieved.
  3. Normal variables provide direct access to their own values; whereas a pointer indirectly accesses the value of a variable to which it points.
  4. The indirection operator (*) is used in two distinct ways with pointers: declaration and dereference.
  5. When a pointer is declared, the star indicates that it is a pointer, not a normal variable.
  6. When the pointer is dereferenced, the indirection operator indicates that the value at that memory location stored in the pointer is to be accessed rather than the address itself.
  7. It should also be noted that * is the same operator which can be used as the multiplication operator. The compiler knows which operator to call, based on the context.
  8. The ‘&’ is the address operator, and it represents the address of the variable. The address of any variable is a whole number. The operator ‘&’ immediately preceding the variable returns the address of the variable. In the below given example, ‘&’ immediately precedes the variable ‘num,’ which provides the address of the variable.

13.1 Write a program to display the address of the variable.

#include<iostream.h>

#include<conio.h>

main()

{

int n;

clrscr();

cout<<“Enter a Number = ”;

cin>>n;

cout<<“Value of n = ”<<n;

cout<<“Address of n= ” <<(unsigned)&n;

getche();

}

OUTPUT

Enter a Number = 10

Value of n = 10

Address of n=4068

Explanation: The memory location of a variable is system dependent. Hence, the address of a variable cannot be predicted immediately. In the above example, the address of the variable ‘n’ that is observed is 4068. In Figure 13.2, three blocks are shown to be related to the above program. The first block contains the variable name. The second block represents the value of the variable. The third block is the address of the variable ‘n,’ where 10 is stored. Here, 4068 is the memory address. The address of the variable depends on various things; for instance, memory model, addressing scheme, and present system settings.

Fig. 13.2

Fig. 13.2 Variable and its memory address

13.2 Write a program to declare a pointer. Display the value and address of the variable-using pointer.

#include<stdio.h>

#include<iostream.h>

#include<conio.h>

void main()

{

int *p;

int x=10;

p=&x;

clrscr();

printf (“ x=%d&x=%u (Using printf())”,x,p);

cout<<“ x=”<<x <<“ &x=”<< &x <<“(Using cout())”;

printf (“ x=%d&x=%u (Using pointer)”,*p,p);

cout<<“ *p=”<<*p <<“ &p=” <<p <<“ (Contents of pointer)”;

}

OUTPUT

 

x=10

&x = 65524

(Using printf())

 

x=10

&x = 0x8f94fff4

(Using cout())

 

x=10

&x = 65524

(Using pointer)

 

*p=10

&p = 0x8f94fff4

(Contents of pointer)

Explanation: In the above program, *p is an integer pointer and x is an integer variable. The address of variable x is assigned to pointer p. Ampersand (&) operator preceded with a variable displays the memory location of that variable. The printf() and cout() statements display addresses in different formats. The printf() statement displays the address as an unsigned integer, whereas the cout() statement displays the address in a hexadecimal format. We can access the contents of variable x using pointer p. The output of the program is as shown above.

 

13.3 Write a program to display memory address of a variable. Type cast the memory address from hexadecimal to unsigned integer.      

#include<iostream.h>

#include<conio.h>

void main()

{

int a;

float b;

char c;

clrscr();

cout<<“ Enter integer number = ”;

cin>>a;

cout<<“ Enter float number = ”;

cin>>b;

cout<<“ Enter character = ”;

cin>>c;

cout<<“ The entered int is = ”<<a;

cout<<“ The entered float is = ”<<b;

cout<<“ The entered char is = ”<<c;

cout<< “ The entered number is stored at location = ” <<(unsigned)&a;

cout<< “ The entered float is stored at location= ”<<(unsigned)&b;

cout<<“ The entered char is stored at location = ”<<(unsigned)&c;

getche();

}

OUTPUT

Enter integer number = 34

Enter float number = 343.34

Enter character = g

The entered int is = 34

The entered float is = 343.339996

The entered char is = g

The entered number is stored at location = 4096

The entered float is stored at location = 4092

The entered char is stored at location = 4091

Explanation: In the above program, variables a, b, and c of int, float, and char type are declared. The entered values are displayed along with their addresses. The addresses of the variables are displayed by a preceding ampersand (&) operator with a variable name. The type-casting syntax (unsigned) is done to type cast the hexadecimal address into an unsigned integer.

Here, you can observe the addresses in descending order. This is because all automatic variables are stored in a stack. The stack always starts from top to lower memory addresses.

13.4  ARITHMETIC OPERATIONS WITH POINTERS

We can perform different arithmetic operations by using pointers. Increment, decrement, prefix, and postfix operations can be performed with pointers. The effects of these operations are shown in Table 13.1.

 

Table 13.1 Pointers and Arithmetic Operations

Table 13.1

From the above table, while referring to the first entry, we can observe that on increment of the pointer variable for integers, the address is incremented by two; that is, 4046 is the original address and on increment, its value will be 4048, because integers require two bytes. Similarly, when the pointer variable for integer is decreased, its address 4048 becomes 4046.

Similarly, for characters, floating point numbers and long integers require 1, 4, and 4 bytes, respectively. After the effect of increment and decrement, the memory locations are shown in Table 13.1.

The following program explains the increase and decrease of pointers:

 

13.4 Program on pointer incrementation and decrementation.

#include<iostream.h>

#include<conio.h>

int main()

{

clrscr();

int x=10;

int *p;

p=&x;

cout<<“ Address of p:”<<unsigned(p);

p=p+4;

cout<<“ Address of p:”<<unsigned(p);

p=p-2;

cout<<“ Address of p:”<<unsigned(p);

return 0;

}

OUTPUT

Address of p:65524

Address of p:65532

Address of p:65528

Explanation: In the above program, p holds the address of x. The initial address of x is 65524. When p is incremented by 4, it means that the address is increased by 8, because each integer needs two bytes. Here, the address obtained is 65532. Similarly, when the address of x is decreased to 2, the address finally obtained is 65528.

 

13.5 Program on changing the values of variables using pointer.

#include<iostream.h>

#include<conio.h>

int main()

{

clrscr();

int x=10;

int *p;

p=&x;

cout<<“ Value of x:”<<*p;

*p=*p+10;

cout<<“ Value of x:”<<*p;

*p=*p-2;

cout<<“ Value of x:”<<*p;

return 0;

}

OUTPUT

Value of x:10

Value of x:20

Value of x:18

Explanation: In the above program using pointers, the value of the variable x is first increased and then decreased.

13.5  POINTER TO POINTER

Pointer to pointer is a pointer that stores the address of another pointer. There can be a chain of pointers depending on applications/requirements. In Figure 13.3, x is a simple variable, p is a pointer to the variable x, and q is a pointer to x. The values of variables ‘x,* p, and **q’ are shown in the boxes, and their addresses are shown outside the boxes.

Fig. 13.3 Pointer to pointer

13.6 Program to demonstrate the concept of pointer to pointer.

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int x=10;

int *p;

int **q;

p=&x;

q=&p;

cout<<“ Value of x =”<<x;

cout<<“ Value of x = ”<<*p;

cout<<“ Value of x = ”<<**q;

cout<<“ Adderss of x ”<<unsigned(*q);

cout<<“ Adderss of x ”<<unsigned(p);

cout<<“ Adderss of x ”<<unsigned(&x);

cout<<“ Adderss of p ”<<unsigned(&p);

cout<<“ Adderss of p ”<<unsigned(q);

cout<<“ Adderss of q ”<<unsigned(&q);

}

OUTPUT

Value of x =10

Value of x = 10

Value of x = 10

Adderss of x 65524

Adderss of x 65524

Adderss of x 65524

Adderss of p 65522

Adderss of p 65522

Adderss of q 65520

The program on pointer to pointer is as follows:

Explanation: In the above program, the value of x is initialized as 10. The same value is displayed with the first three cout statements. p holds the address of x, q holds the address of p, and the same are displayed using pointers.

13.6  void POINTERS

Pointers can also be declared as void type. void pointers cannot be dereferenced without explicit-type conversion. This is because, being void, the compiler cannot determine the size of the object that the pointer points to. Though void pointer declaration is possible, void variable declaration is not allowed. Thus, the declaration void p will display an error message “Size of ‘p’ is unknown or zero” after compilation.

It is not possible to declare void variables such as pointers. A pointer points to an existing entity. A void pointer can point to any type of variable with proper type casting. The size of the void pointer displayed will be two. When a pointer is declared as void, two bytes are allocated to it. Later, using type casting, the number of bytes can be allocated or de-allocated. void variables cannot be declared, because memory is not allocated to them, and there is no place to store the address. Therefore, void variables cannot actually serve the purpose they are made for.

 

13.7 Write a program to declare a void pointer. Assign address of int, float, and char variables to the void pointer using typecasting method. Display the contents of various variables.

// void pointers //

#include<stdio.h>

#include<iostream.h>

#include<conio.h>

int p;

float d;

char c;

void *pt = &p;        // pt points to p

void main (void)

{

clrscr();

*(int *) pt = 12;

cout<<“ p=”<<p;

pt = &d;        // pt points to d

*(float *)pt = 5.4;

cout<<“ r=”<<d;

pt=&c;        // pt points to c

*(char* )pt=‘S’;

cout<<“ c=”<<c;

}

OUTPUT

p=12

r=5.4

c=S

Explanation: In the above example, variables p, d, and c are variables of type int, float, and char, respectively. Pointer pt is a pointer of type void. These entire variables are declared before main(). The pointer is initialized with the address of integer variable p, that is, the pointer p points to variable x.

The statement *(int *) pt = 12 assigns the integer value 12 to pointer pt, that is, to a variable p. The contents of the variable p are displayed using the succeeding statement. The declaration *(int *) tells the compiler that the value assigned is of integer type. Thus, the assignment of float and char type is carried out. The statements *(int *) pt = 12, *(float *) pt = 5.4, and *(char*) pt = ‘S’ help the compiler exactly determine the size of data type.

13.7  wild POINTERS

Pointers are used to store memory addresses. An improper use of pointers creates many errors in the program. Hence, pointers should be handled cautiously. When a pointer points to an unallocated memory location or to a data value whose memory is de-allocated, such a pointer is called a wild pointer. The wild pointer generates garbage memory location and pendent reference.

When a pointer pointing to a memory location vanishes, the memory is transformed into garbage memory. It indicates that a memory location exists but a pointer is destroyed. This happens when the memory is not de-allocated explicitly.

The pointer becomes a wild pointer due to the following reasons:

  1. Pointer declared but not initialized
  2. Pointer alteration
  3. Accessing destroyed data
  1. When a pointer is declared and not initialized, it holds an illicit address. It is very hard to manipulate such a pointer. Consider the following example:

     

    13.8 Write a program to use wild pointer.      image

    #include<iostream.h>

    #include<conio.h>

    int main()

    {

    clrscr();

    int *x;

    for (int k=0;k<10;k++)

    cout<<x[k]<<“ ”;

    return 0;

    }

    OUTPUT

    28005 27760 29793 29541 29728 8303 25954 28704 25205 26988

    Explanation: In the above program, pointer x is declared and not initialized. Using for loop, the location-containing pointer is increased, and successive addresses are displayed.

  2. The careless assignment of a new memory location in a pointer is called pointer alternation. This happens when another wild pointer accesses the location of a legal pointer and converts the legal pointer into a wild one. Consider the following program:
  3. Sometimes, the pointers attempt to access the data that no longer have life. The following program illustrates this:

13.9 Write a program to display the output when a pointer is accessing a temporary data of the memory.

#include<iostream.h>

#include<conio.h>

char*instring();

char*inchar();

void main()

{

clrscr();

char *ps,*pc;

ps=instring();

pc=inchar();

cout<<“ String : ”<<*ps<<endl;

cout<<“ Character : ”<<*pc<<endl;

}

char *instring()

{

char str[]= “cpp”;

return str; }

char *inchar()

{

char g;

g=‘D’;

return &g; }

OUTPUT

String : c

Character : .

Explanation: In the above program, ps and pc are character pointers. The function instring() and inchar() returns references (base address of the string or character), and they are stored in the pointers ps and pc, respectively. When the control exits from these functions and returns to main(), local variables inside the user-defend functions are destroyed. Thus, the pointers ps and pc point to the data that are destroyed. The contents displayed of the pointers will be as shown in the output.

13.8  POINTER TO CLASS

We know that a pointer is a variable that holds the address of another data variable. The variable may be of any data type, that is, int, float, or double. In the same way, we can also define pointer to class. Here, the starting address of the member variables can be accessed. Thus, such pointers are called class pointers.

 

Example:

class book

{char name [25];

char author [25];

int pages;

};

(a) class book *ptr;

or

struct book *ptr;

In the above example, *ptr is a pointer to a class book. Both statements (a) and (b) are valid. The syntax for using pointers with members is as given below.

 

1) ptr->name 2) ptr->author 3) ptr->pages.

By executing these three statements, the starting address of each member can be estimated.

 

13.10 Write a program declares a class. Declare pointer to class. Initialize and display the contents of the class member.      image

#include<iostream.h>

#include<conio.h>

void main()

{

      class man

      {

        public :

        char name[10];

        int age;

      };

man m={“RAVINDRA”, 15};

man *ptr;

ptr=&(man)m;

// *ptr=(man)m;

// *ptr=man(m);

// *ptr=m;

// ptr=&m;

clrscr();

cout<<“ ” <<m.name <<“ ”<<m.age;

cout<<“ ”<<ptr->name<<“ ”<<ptr->age;

}

OUTPUT

RAVINDRA 15

RAVINDRA 15

Explanation: In the above program, the pointer ptr points to the object m. The statement ptr = &(man) m assigns the address of the first member element of the class to the pointer ptr. Using the dot operator and arrow operator, contents can be displayed. The display of the class contents is possible, because the class variables are declared as public. The below given statements can also be used to assign the address of the object to the pointer.

 

  • ptr=&(man)m;
  • *ptr=(man)m;
  • *ptr=man(m);
  • *ptr=m;
  • ptr=&m;
13.9  POINTER TO OBJECT

Similar to variables, objects also have an address. A pointer can point to a specified object. The following program illustrates this:

 

13.11 Write a program to declare an object and pointer to the class. Invoke the member functions using pointer.

#include<iostream.h>

#include<conio.h>

class Bill

{

int qty;

float price;

float amount;

public :

void getdata (int a, float b, float c)

{

        qty=a;

        price=b;

        amount=c;

}

void show()

{

      cout<<“Quantity : ” <<qty <<“ ”;

      cout<<“Price : ” <<price <<“ ”;

      cout<<“Amount : ” <<amount <<“ ”;

}

};

int main()

{

clrscr();

Bill s;

Bill *ptr =&s;

ptr->getdata(45,10.25,45*10.25);

(*ptr).show();

return 0;

}

OUTPUT

 

Quantity

: 45

Price

: 10.25

Amount

: 461.25

Explanation: In the above program, the class Bill contains two float and one int members. The class Bill also contains the member function getdata() and show() to read and display the data. In function main(), s is an object of class Bill, and ptr is a pointer of the same class. The address of object s is assigned to pointer ptr. Using pointer ptr with arrow operator (->) and dot operator (.), members and functions are invoked. The statements used for invoking functions are as given below.

 

ptr->getdata (45,10.25,45*10.25);

(*ptr).show();

Here, both the pointer declarations are valid. In the second statement, ptr is enclosed in brackets, because the dot operator (.) has higher precedence as compared with the indirection operator (*). The output of the program is as shown above.

 

13.12 Write a program to create dynamically an array of objects of class type. Use new operator.

#include<iostream.h>

#include<conio.h>

class Bill

{

int qty;

float price;

float amount;

public :

void getdata (int a, float b, float c)

{

        qty=a;

        price=b;

        amount=c;

}

void show()

{

    cout<<“Quantity : ” <<qty <<“ ”;

    cout<<“Price : ” <<price <<“ ”;

    cout<<“Amount : ” <<amount <<” ”;

}

};

int main()

{

clrscr();

Bill *s= new Bill[2];

Bill *d =s;

int x,i;

float y;

for (i=0;i<2;i++)

{

      cout<<“ Enter Quantity and Price : ”;

      cin>>x >>y;

      s->getdata(x,y,x*y);

      s++;

}

for (i=0;i<2;i++)

{

      cout<<endl;

      d->show();

      d++;

}

return 0;

}

OUTPUT

Enter Quantity and Price : 5 5.3

Enter Quantity and Price : 8 9.5

Quantity : 5

Price : 5.3

Amount : 26.5

Quantity : 8

Price : 9.5

Amount : 76

Explanation: In the above program, the class Bill is similar to that in the previous example. In main(), using new memory allocation operator, the memory required for two objects is allocated to pointer s, that is, 10 bytes. The first for loop accepts the data through the keyboard. Immediately after this, the data are sent to the member function getdata(). The pointer s is incremented. After incrimination, it points to the next memory location of its type. Thus, two records are read through the keyboard. The second for loop is used to display the contents on the screen. Here, the function show() is invoked. The logic used is similar to that used in the first loop. The functions are invoked using pointers, and this has been explained in the previous example.

13.10  THE this POINTER

Use of this pointer is now outdated. Objects are used to invoke the non-static member function of the class. For example, if p is an object of class P and get() is a member function of P, the statement p.get() is used to call the function. The statement p.get() operates on p. In the same way, if ptr is a pointer to a P object, the function called ptr->get() operates on *ptr.

However, the question is, how does the member function get() to understand which p it is functioning on? C++ compiler provides get() with a pointer to p called this. The pointer this is transferred as an unseen parameter in all calls to non-static member functions. The keyword this is a local variable that is always present in the body of any non-static member function.

The keyword this does not need to be declared. The pointer is rarely referred to explicitly in a function definition. However, it is used implicitly within the function for member references. For example, if p.get(k) is called, where k is a member of P, the keyword this is set to &p and k is set to this->k, which is equivalent to p.k.

 

13.13 Write a program to use this pointer and return pointer reference.

#include<iostream.h>

#include<conio.h>

class number

{

int num;

public :

void input()

{

      cout<<“ Enter a Number : ”;

      cin>>num;

}

void show()

{ cout<<“ The Minimum Number : ”<<num; }

number min( number t)

{ if (t.num<num)

      return t;

      else

      return *this; }

};

void main()

{

clrscr();

number n,n1,n2;

n1.input();

n2.input();

n=n1.min(n2);

n.show();

}

OUTPUT

Enter a Number : 152

Enter a Number : 458

The Minimum Number : 152

Explanation: In the above program, the class number contains one integer number variable num. The class also contains member functions input(), show() and min(). The input() function reads an integer through the keyboard. The show() function displays the contents on the screen. The min() function finds a minimum number out of two. The variables n, n1, and n2 are objects of class number.

In function main(), the objects n1 and n2 call the function input() and read integers. Both the objects n1 and n2 are passed to function min() with the statement n = n1.min(n2). The object n receives the returned value by the function min(). The object n1 calls the function min(). The object n2 is passed as an argument in the function min().

In function num(), the formal object t receives the contents of argument n2. In the same function, the object n1 is also accessible. As studied earlier, the pointer this is present in the body of every non-static member function, and it points to the object n1. Using the pointer this, we can access the individual member variable of object n1. The if statement compares the two objects, and the return statement returns the smaller object.

 

13.14 Write a program to enter name and age of two persons. Find the elder person. Use this pointer.      image

#include<iostream.h>

#include<conio.h>

class name

{

      char str[15];

      int age;

      public:

void input()

{

        cout<<“ Enter Name and age : ”;

        cin>>str;

        cin>>age;

}

void show()

{

    cout<<“ Elder person ”;

    cout<<“ Name: ”<<str;

    cout<<“ Age: ”<<age;

  }

name display( name x)

{

  cout<<“ Contents of object n1 (this pointer)”;

  cout<<“ Name:” <<this->str;

  cout<<“ Age:” <<this->age;

  cout<<“ Contents of object n2 (x)”;

  cout<<“ Name: ” <<x.str;

  cout<<“ Age: ” <<x.age;

  if (this->age>x.age)

  return *this;

  else

  return x;

}

};

void main()

{

clrscr();

name n,n1,n2;

n1.input();

n2.input();

n=n1.display(n2);

n.show();

}

OUTPUT

Enter Name and age : Mahesh 25

Enter Name and age : Suresh 30

Contents of object n1(this pointer)

Name : Mahesh

Age : 25

Contents of object n2 (x)

Name : Suresh

Age : 30

Elder person

Name : Suresh

Age : 30

Explanation: The above program is similar to the previous one. Here, contents of explicitly and implicitly passed objects are displayed. The this pointer points to the hidden argument (implicit argument). The if statement compares the member variable age of both the objects and returns the greater one. The object n collects the return value of function display() and calls the function show(). The function show() displays the contents of object n. Working of this pointer is illustrated in Fig. 13.4.

Fig. 13.4 Working of this pointer

13.11  POINTER TO DERIVED CLASSES AND BASE CLASS

It is possible to declare a pointer that points to the base class as well as the derived class. One pointer can point to different classes. For example, X is a base class and Y is a derived class. The pointer pointing to X can also point to Y.

 

13.15 Write a program to declare a pointer to the base class and access the member variable of base and derived class.

// Pointer to base object //

#include<iostream.h>

#include<conio.h>

class A

{

        public :

        int b;

        void display()

        {

        cout<<“b = ” <<b <<“ ”;

        }

};

class B : public A

{

public :

int d;

void display()

{

cout<<“b= ” <<b <<“ ” <<“ d=”<<d <<“ ”;

}

  };

  main()

  {

  clrscr();

  A *cp;

  A base;

  cp=&base;

  cp->b=100;

// cp->d=200; Not Accessible

  cout<<“ cp points to the base object ”;

  cp->display();

  B b;

  cout<<“ cp points to the derived class ”;

  cp=&b;

  cp->b=150;

// cp->d=300; Not accessible

    cp->display();

  return 0;

}

OUTPUT

cp points to the base object

b = 100

cp points to the derived class

b = 150

Explanation: In the above program, A and B are two classes with a one-integer member variable and member function. The class B is derived from class A. The pointer cp points to the class A. The variable base is an object of the class A. The address of the object base is assigned to pointer cp. The pointer cp can access the member variable b, a member of the base class, but cannot access the variable d, a member of the derived class. Thus, the following statement is invalid:

 

a) cp->d = 200;

The variable b is an object of class B. The address of object b is assigned to the pointer cp. However, b is an object of the derived class; access to the member variable d is not possible. Thus, the following statement is invalid:

 

b) cp->d = 300;

Here, cp is a pointer of the base class, and it cannot access the members of the derived class.

 

13.16 Write a program to declare a pointer to the derived class and access the member variable of base and derived class.

// Pointer to derived object //

#include<iostream.h>

#include<conio.h>

class A

{

      public :

      int b;

      void display()

{

cout<<“b = ” <<b <<“ ”;

}

};

class B : public A

{

public:

int d;

void display()

{

cout<<“ b= ” <<b <<“ ” <<“ d= ”<<d <<“ ”;

}

};

main()

{

clrscr();

B *cp;

B b;

cp=&b;

cp->b=100;

cp->d=350;

cout<<“ cp points to the derived object ”;

cp->display();

return 0;

}

OUTPUT

cp points to the derived object

b= 100

d= 350

Explanation: The above program is similar to the previous one. The only difference is that the pointer cp points to the object of the derived class. The pointer cp is a pointer of the class B. The variable b is an object of the class B. The address of b is assigned to the pointer cp. The pointer cp can access the member variables of both base and derived classes. The output of the program is shown above.

 

13.17 Write a program to declare pointer to class. Invoke constructor to initialize data member. Call member function using pointer.

#include<iostream.h>

#include<conio.h>

class A

{

private :

int a;

public:

A()

{

      a=20;

}

void show()

{

cout<<“ a = ”<<this->a ;

}

};

int main()

{

clrscr();

A *p,*q;

q=p->A::A();

p->show();

q->show();

return 0;

}

OUTPUT

a = 20

a = 20

Explanation: In the above program, *p and *q are pointers of class A. The constructor is not executed for pointers. The constructor of class A is explicitly called pointer p. Data members of both pointer objects p and q are initialized to 20. The statements p->show() and q->show() are used to invoke the member function using pointers. The output of the program is shown above.

 

13.18 Write a program to declare object and pointer to class. Assign value of object to pointer to object. Display their values. Also carry out conversion from basic type to class type.

#include<iostream.h>

#include<conio.h>

#include<alloc.h>

class A

{

private :

int a;

public:

A()

{

      a=30;

}

void show() { cout<<“ a = ”<<a ;}

A (int x)

{

      this->a=x;

}

};

int main()

{

clrscr();

A k,*b,a;

*b=50;

k=*b;

b->show();

a.show();

k.show();

return 0;

}

OUTPUT

a = 50

a = 30

a = 50

Explanation: In the above program, a and k are objects of class A. The *b is a pointer object. The objects a and k are initialized to 30 by the constructor. The statement *b = 50 assigns 50 to data member a. This is carried out by the conversion constructor A (int). The value of *b is assigned to object k. The member function show() is called by all the three objects, and the output of the program is as given above.

13.12  POINTER TO MEMBERS

It is possible to obtain the address of a member variable and store it to a pointer. The following programs explain how to obtain address and to access member variables with pointers.

 

13.19 Write a program to initialize and display the contents of the structure using dot (.) and arrow (->) operator.

#include<iostream.h>

#include<conio.h>

int main()

{

clrscr();

struct c

{

char *name;

};

      c b, *bp;

      bp->name=“ CPP”;

      b.name=“C &”;

      cout<<b.name;

      cout<<bp->name;

      return 0;

}

OUTPUT

C & CPP

Explanation: In the above program, structure c is declared. The variable b is the object, and bp is a pointer object of structure c. The elements are initialized and displayed using dot (.) and arrow (->) operators. These are the traditional operators that are commonly used in C. C++ allows two new operators .* and ->* to carry out the same task. These c++ operators are recognized as pointers of member operators.

 

13.20 Write a program to initialize and display the contents of the structure using .* and arrow ->* operators.

#include<iostream.h>

#include<conio.h>

struct data

{

int x;

float y;

};

int main()

{

clrscr();

int data ::*xp=&data::x;

float data::*yp=&data::y;

data d={11,1.14};

cout<<endl<<d.*xp<<endl<<d.*yp;

data *pp;

pp=&d;

cout<<endl<<pp->*xp<<endl<<pp->*yp;

d.*xp=22;

pp->*yp=8.25;

cout<<endl<<d.*xp<<endl<<d.*yp;

cout<<endl<<pp->*xp<<endl<<pp->*yp;

return 0;

}

OUTPUT

11

1.14

11

1.14

22

8.25

22

8.25

Explanation: In the above program, struct data is defined, and it has two data members of integer and float type. Consider the following statements:

 

int data ::*xp = &data::x;

float data::*yp = &data::y;

The *xp and * yp are pointers. The class name followed by scope access operator points to the fact that they are pointers to member variables of structure int x and float y. The rest of the statement initializes the pointers with addresses of the x and y, respectively.

The rest of the program uses operators .* and ->* to initialize and access the member elements in the same fashion as the operator dot (.) and arrow (->).

 

13.21 Write a program to declare and initialize an array. Access and display the elements using .* and ->* operators.

#include<iostream.h>

#include<conio.h>

struct data

{

int x;

float y;

};

int main()

{

clrscr();

int data ::*xp=&data::x;

float data::*yp=&data::y;

data darr[]={{12,2.5},

{58,2.4},

{15,5.7} };

for (int j=0;j<=2;j++)

cout<<endl<<darr[j].*xp<<“ ”<<darr[j].*yp;

return 0;

}

OUTPUT

12  2.5

58  2.4

15  5.7

Explanation: The above program is similar to the previous one. An array darr[] is initialized. The for loop and the operator .* access the elements, and the elements are displayed on the console.

 

13.22 Write a program to declare variables and pointers as members of class and access them using pointer to members.

#include<iostream.h>

#include<conio.h>

class data

{

public:

int x;

float y;

int *z;

float *k;

int **l;

float **m;

};

void main()

{

clrscr();

int data::*xp=&data::x;

float data ::*yp=&data::y;

int *data::*zp=&data::z;

float *data::*kp=&data::k;

int **data::*lp=&data::l;

float **data::*mp=&data::m;

data ob={51,4.58,&ob.x,&ob.y,&ob.z,&ob.k};

data *pp;

pp=&ob;

cout<<endl<<ob.*xp<<endl<<ob.*yp;

cout<<endl<<*(ob.*zp)<<endl<<*(ob.*kp);

cout<<endl<<**(ob.*lp)<<endl<<**(ob.*mp);

cout<<endl<<pp->*xp<<endl<<pp->*yp;

cout<<endl<<*(pp->*zp)<<endl<<*(pp->*kp);

cout<<endl<<**(pp->*lp)<<endl<<**(pp->*mp);

*(ob.*zp)=11;

**(pp->*mp)=8.24;

cout<<endl<<ob.*xp<<endl<<ob.*yp;

}

OUTPUT

51

4.58

51

4.58

51

4.58

51

4.58

51

4.58

51

4.58

11

8.24

Explanation: In the above program, the class and data are declared, and all members are public. The ob is an object of the class data, and it is initialized. The variable pp is a pointer, and it is initialized with the address of the object ob. The remaining program statements use the pointers of member operators and display the contents of the class on the screen.

 

TIP

Pointers of members are not associated with any particular object.

13.23 Write a program that invokes member function using pointer to functions.

#include<iostream.h>

#include<conio.h>

class data

{

public:

void joy1()

{

cout<<endl<<(unsigned)this<<“ in joy1”;

}

void joy2()

{

cout<<endl<<(unsigned)this<<“ in joy2”;

}

void joy3()

{

cout<<endl<<(unsigned)this<<“ in joy3” <<endl;

}

};

void main()

{

clrscr();

data od[4];

void (data ::*m[3])()={&data::joy1,&data::joy2,&data::joy3

};

for (int x=0;x<=3;x++)

{

for (int y=0;y<=2;y++) (od[x].*m[y])();

}

}

OUTPUT

65522 in joy1

65522 in joy2

65522 in joy3

65523 in joy1

65523 in joy2

65523 in joy3

65524 in joy1

65524 in joy2

65524 in joy3

65525 in joy1

65525 in joy2

65525 in joy3

Explanation: In the above program, class data have three-member variables joy1, joy2, and joy3. The array m[3])() holds the addresses of member functions. The nested for loop and statement within it invokes member functions.

 

13.24 Write a program to declare pointer to member variable and display the contents of the variable.

#include<iostream.h>

#include<conio.h>

class A

{

public :

int x;

int y;

int z;

};

void main()

{

clrscr();

A a;

int *p;

a.x=5;

a.y=10;

a.z=15;

p=&a.x;

cout<<endl<<“x= ”<<*p;

p++;

cout<<endl<<“y= ”<<*p;

p++;

cout<<endl<<“z= ”<<*p;

}

OUTPUT

x= 5

y= 10

z= 15

Explanation: In the above program, the class A is declared with three public member variables x, y, and z. In function main(), a is an object of class A, and p is an integer pointer. The three-member variables are initialized with 5, 10, and 15 using the assignment operation.

The address of variable x is assigned to a pointer. The postfix increase operation gives successive memory locations, and values stored at those locations are accessed and displayed. Thus, member variables are stored in successive memory locations. Using the same concept, we can also access private members.

13.13  ACCESSING PRIVATE MEMBERS WITH POINTERS

In the previous topic, we learned how to access public members of a class using pointers. The public and private member variables are stored in successive memory locations. The following program explains how private members can also be accessed using pointers.

 

13.25 Write a program to access private members like public members of the class using pointers.

#include<iostream.h>

#include<conio.h>

class A

{

private:

int j;

public :

int x;

int y;

int z;

A()

{

j=20;}

};

void main()

{

clrscr();

A a;

int *p;

a.x=11;

a.y=10;

a.z=15;

p=&a.x;

p--;

cout<<endl<<“j =”<<*p;

p++;

cout<<endl<<“x= ”<<*p;

p++;

cout<<endl<<“y= ”<<*p;

p++;

cout<<endl<<“z= ”<<*p;

}

OUTPUT

j = 20

x = 11

y = 10

z = 15

Explanation: This program is similar to the previous one. In addition, the class A has one private member variable. The private member variables can be accessed using functions, and no direct access is available to them. However, using pointers, we can access them as in the case of public member variables.

13.14  DIRECT ACCESS TO PRIVATE MEMBERS

So far, we have initialized private members of the class using the constructor or member function of the same class. In the previous sub-topic, we also learned how private members of the class can be accessed using pointers. In the same way, we can initialize private members and display them. One can do this by obtaining the address of any public member variable and using the address of the object. The address of the object contains the address of the first element. Programs dealing with this are given below.

 

13.26 Write a program to initialize the private members and display them without using member functions.

#include<iostream.h>

#include<conio.h>

class A

{

private :

int x;

int y;

};

void main()

{

clrscr();

A a;

int *p=(int*)&a;

*p=3;

p++;

*p=9;

p--;

cout<<endl <<“x= ”<<*p;

p++;

cout<<endl<<“y= ”<<*p;

}

OUTPUT

x= 3

y= 9

Explanation: In the above program, a is an object of class A. The address of the object is assigned to integer pointer p by applying type casting. The pointer p points to private member x. Integer value is assigned to *p, that is, x. Address of object a is increased and by accessing the memory location value 9 is assigned to y. The p- - statement sets the memory location of x. Using the cout statement contains of x is displayed.

 

13.27 Write a program to initialize and display private members using pointers.

#include<iostream.h>

#include<conio.h>

class A

{

private :

int x;

int y;

};

class B : public A

{

public :

int z;

void show(int *k)

{

cout<<“x= ”<<*k << “ y =”<<*(k+1) <<“ z=”<<*(k+2);

}

};

void main()

{

clrscr(); // clears the screen

B b; // object declaration

int *p; // pointer declaration

p=&b.z; // address of z is assigned to p

*p=3; // initialization of z

p--; // points to previous location

*p=4; // initialization of y

p--; // points to previous location

*p=5; // initialization of x

b.show(p); // passing address of x to function show()

}

OUTPUT

x= 5 y =4 z=3

Explanation: In the above program, class A has two private integer member variables x and y. The class B has a one-integer variable z, and it is derived from class A. In function main(), b is an object of class B, and p is a pointer. The pointer p is initialized with the address of public member variable z. The memory location of p is initialized with 3 (initialization of z). By applying a decrease operation on pointers, previous locations are accessed, and initializations of memory locations are done (initialization of y and x). The address of x is passed to function show(). By applying an increase operation with the pointer address, the successive elements are displayed.

13.15  ADDRESSES OF OBJECTS AND void POINTERS

The size of an object is equal to the number of total member variables declared inside the class. The size of the member function is not considered in the case of objects. The object itself contains the address of first member variables. By obtaining the address, we can access the member variables directly, irrespective of whether they are private or public. The address of the object cannot be assigned to the pointer of the same type. This is because an increase operation on pointers will set the address of the object according to its size (size of object = size of total member variables). The address of the object should be increased according to the basic data type. To overcome this situation, a void pointer is useful. The type of void pointer can be changed at run time using type-casting syntax. Thus, all the member variables can be accessed directly. Consider the following program:

 

13.28 Write a program to declare void pointers and access member variables using void pointers.

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

class A

{

protected:

int x;

int y;

};

class B : public A

{

public :

int z;

B()

{

x=10; y=20; z=30;

}

};

void main()

{

clrscr(); // clears the screen

B b; // object declaration

int j; // declaration of integer j

void *p=&b; // declaration & initialization of void pointer

for (j=0;j<3;j++) // for loop executed for three times

printf (“ member variable [%d] = %d”,j+1,*((int*)p+j));

// cout<<j+1<<“ ” <<*((int*)p+j)<<endl;

}

OUTPUT

member variable [1] = 10

member variable [2] = 20

member variable [3] = 30

Explanation: In the above program, the b is an object of the derived class B. The address of the object b is assigned to the void pointer p. Using the for loop and the type-casting operation, integer values are accessed. The address of the void pointer is increased by two bytes. The cout statement now and then will not display the result accurately, and, hence, the printf() statement is used.

The type-casting operation is done according to the data type of member variables. Here, all the class-member variables are of integer type. In any case, the class contains variables of integer, float, and char type. Thus, it is necessary to type cast according to the sequence of the member variables.

13.16  MORE PROGRAMS

13.29 Write a program to declare the array of class objects. Use constructors and destructors. Read names and display with their length.

#include<iostream.h>

#include<conio.h>

#include<string.h>

#include<iomanip.h>

class word

{

private :

char name[20];

int len;

public :

word()

{

      cout<<“ Enter Name : ”;

      cin.getline(name,20);

      len=strlen(name);

}

~word()

{

      cout<<name <<“(“<<len<<”) ”;

}

};

int main()

{

clrscr();

word w[5];

cout<<“ Entered names with their length ”;

return 0;

}

OUTPUT

Enter Name : Sourav

Enter Name : Sachin

Enter Name : Rahul

Enter Name : Ajay

Enter Name : Ajit

Entered names with their length

Ajit(4)

Ajay(4)

Rahul(5)

Sachin(6)

Sourav(6)

Explanation: In the above program, the class word has one data member of character-type array. The class also contains a constructor and a destructor. In function main(), an array of five objects is defined. The constructor executes five times, and names are entered through the keyboard. The constructor also calculates the length of the entered string. The destructor displays the string and its length.

 

13.30 Write a program to create array of objects. Initialize and display them using non-member function.

#include<iostream.h>

#include<conio.h>

class A

{

      public:

          char c;

          int i;

          float f;

      A()

      {

          cout<<“ Enter char, int and float value ”;

          cin>>c>>i>>f;

      }

};

int main()

{

      void out(A);

      clrscr();

      A a[]={A(),A()};

      out(a[0]);

      out (a[1]);

      return 0;

}

void out (A c)

{

cout<<“ char value = ”<<c.c;

cout<<“ int value = ”<<c.i;

cout<<“ float value = ”<<c.f;

cout<<“ ”;

}

OUTPUT

Enter char, int and float value T 2 2.5

Enter char, int and float value J 4 3.7

char value = T

int value = 2

float value = 2.5

char value = J

int value = 4

float value = 3.7

Explanation: In the above program, class A holds three elements c, i, and f of char, int, and float data type. The class A also has a constructor that is used for the initialization of objects. The initialization of objects is nothing but assigning value to the associated member elements of the class. In main() function array of object is declared. The constructor of the class is invoked and values to the member variables are assigned. The class A is defined before function main(). Another non-member function out() is defined for displaying the contents of the object. Array elements are passed to the function out(), and contents are displayed. The out() function has one argument of type class A. The argument receives the copy of the contents of array objects.

 

13.31 Write a program to pass this pointer as argument to the member function and display the contents.

#include<iostream.h>

#include<conio.h>

class A

{

private:

char c;

int i;

float f;

public:

A()

{

      cout<<“ Enter char, int and float value ”;

      cin>>c>>i>>f;

      out(this);

}

void out (A *a )

{

      cout<<“ char value = ”<<a->c;

      cout<<“ int value = ”<<a->i;

      cout<<“ float value = ”<<a->f;

      cout<<“ ”;

}

};

int main()

{

      clrscr();

      A a;

      return 0;

}

OUTPUT

Enter char, int and float value F 2 2.8

char value = F

int value = 2

float value = 2.8

Explanation: In the above program, the pointer this is passed to the member function out(). In function out() using -> operator, the contents of elements are displayed. We know that the this pointer is always present in every member function and it points to the calling object.

 

13.32 Write a program to assign value using this pointer.

#include<iostream.h>

#include<conio.h>

class data

{

private :

int j;

public:

void setv (int v)

{

      j=v;

cout<<“ j = ”<<j;

      this->j=++v;

      cout<<“ j = ”<<j;

}

};

int main()

{

clrscr();

data d;

d.setv(7);

return 0;

}

OUTPUT

j = 7

j = 8

Explanation: In the above program, the class data have only one element, that is, int j. The member function setv() is used to assign the value to the data element. The value passed to the setv() function is assigned to the member variable directly and using this pointer. Before assigning the value using this pointer, the variable v is incremented. The values of j in two assignments are given in the output.

 

13.33 Write a program to enter integer numbers, count them, and make fragments of equal lengths. The fragment length to be entered by the user.

Tip: In case the total number of elements is odd, the last segment contains the remaining elements.

#include<stdio.h>

#include<conio.h>

#include<iostream.h>

main()

{

int *p,*k,s=1;

int j,c=0,f,i=0;

clrscr();

k=p;

printf (“ Enter numbers (0) to exit :”);

while (1)

{

cin>>*p;

if (*p==0) break;

c++;

p++;

}

cout<<endl<<c <<“ elements are entered ”;

cout<<endl<<“ Enter length of fragment : ”;

cin>>f;

cout<<endl<<“Fragment ”<<s<<“ :”;

for (j=0;j<c;j++)

{

i++;

cout<<“ ”<<*(k+j);

if (i==f)

      {

        cout<<“ ”;

        s++;

        cout<<“ Fragment ”<<s<<“ :”;

        i=0;

      }

}

return 0;

}

OUTPUT

Enter numbers (0) to exit :4 5 2 1 3 4 8 7 9 0
9
elements are entered

Enter length of fragment : 2

Fragment 1 : 4 5

Fragment 2 : 2 1

Fragment 3 : 3 4

Fragment 4 : 8 7

Fragment 5 : 9

Explanation: In the above program, pointers p, k and integer variables s, j, c, f, and i are declared. The integer variable s is initialized to one, and i is initialized to zero. The address of pointer p is assigned to k. Using while loop and pointer p, numbers are read through the keyboard. The pointer p is incremented in every iteration, and it points to successive memory locations. The numbers entered are stored in these memory locations. The if statement checks the entered number and if it is zero, control comes out of the loop. The variable c counts the number of elements entered.

The number of elements to be stored in each segment is to be entered through the keyboard. Variable f holds the number of total elements. The for loop executes from zero to c-1. The pointer k and loop variable j are used to access successive memory locations and the elements stored in them from the starting address. The statement cout<<“ ”<<*(k+j) displays elements on the screen.

 

13.34 Write a program to assign different types of data to void pointers. Display the data using void pointers on the screen using typecast syntaxes according to the data type.

#include<iostream.h>

#include<conio.h>

#define SIZE 25

void show ( void *vp, char status)

{

switch(status)

{

          case ‘l’:

          cout<<“ The long integer entered : ”<<*((long*) vp);

          delete vp;

          break;

          case ‘i’:

          cout<<“ The integer entered : ”<<*((int*)vp);

          delete vp;

          break;

          case ‘s’ :

          cout<<“The entred string : ”<<(char*) vp;

          delete vp;

          break;

          case ‘f’:

          cout<<“ The float entered : ”<<*((float*)vp);

          delete vp;

break;

          }

}

void main()

{

clrscr();

int *i;

char *s;

float *f;

long *l;

char choice;

cout<<“ Enter data type (s)tring, (i)nt, (f)loat (l)ong:”;

cin.get(choice);

switch(choice)

{

          case ‘l’ :

          l=new long;

          cout<<“ Enter an long integer : ”;

          cin>>*l;

          show(l,choice);

          break;

          case ‘s’:

          s=new char[SIZE];

          cout<<“ Enter a string :”;

          cin>>s;

          show(s,choice);

          break;

          case ‘i’ :

          i=new int;

          cout<<“ Enter an integer : ”;

          cin>>*i;

          show(i,choice);

          break;

          case ‘f’ :

          f= new float;

          cout<<“ Enter a float : ”;

          cin>>*f;

          show (f,choice);

          break;

          default :

          cout<<“ Invalid choice ” ;

}

}

OUTPUT

Enter data type (s)tring, (i)nt, (f)loat (l)ong :l

Enter an long integer : 52114

The long integer entered : 52114

Explanation: In the above program, the pointers i, s, f, and l of int, char, float, and long type are declared, respectively. The character variable choice is declared. The program prompts the user to enter his/her choice. The switch() case executes the appropriate case according to the user choice. By using new operators, memory is allocated to the respective pointers and again, the program prompts the user to enter data. The data and choice entered by the user are passed to function show(). The function show() contains void pointers. In function show(), the type of void pointer is changed to char, long, int, and float. The type depends on the value of variable choice. Thus, the entered data are displayed.

SUMMARY
  1. Similar to C, in C++, variables are used to hold data values during program execution. When declared, every variable occupies certain memory locations.
  2. Pointers save the memory space. The execution time with pointers is faster, because data are manipulated with the address.
  3. The indirection operator (*) is also called the dereference operator. When a pointer is dereferenced, the value at that address stored by the pointer is retrieved.
  4. The ‘&’ is the address operator, and it represents the address of the variable. The address of any variable is a whole number.
  5. Pointers can also be declared as void type. void pointers cannot be dereferenced without explicit-type conversion. This is because, being void, the compiler cannot determine the size of the object that the pointer points to.
  6. The pointer this is transferred as an unseen parameter in all calls to non-static member functions. The keyword this is a local variable that always presents in the body of any non-static member function.
  7. This chapter covers topics on pointer to derived classes and base class, pointer to members, accessing private members with pointers, direct access to private members, addresses of objects, and void pointers.
  8. More programs are given in this chapter to understand the concepts on pointers.
EXERCISES

(A) Answer the following questions

  1. What are pointers?
  2. What is a void pointer?
  3. What is a wild pointer?
  4. What is a this pointer?
  5. What are the features and uses of pointers?
  6. In which situations does the pointer become harmful?
  7. Explain any two characteristics of pointers.
  8. How can private members be accessed using pointers?
  9. Why is a declaration of void variables not permitted?

(B) Answer the following by selecting the appropriate option

  1. The pointer holds
    1. Address of the variable
    2. Value of the variable
    3. Both (a) and (b)
    4. None of the above
  2. An integer-type pointer can hold only the address of
    1. Integer variable
    2. Float variable
    3. Any variable
    4. None of the above
  3. The address of the variable is displayed by the symbol
    1. &(Ampersand)
    2. * (asterisk)
    3. ! (not operator)
    4. New operator
  4. The size of ( ) object is equal to
    1. Total size of data member variables
    2. Total size of member functions
    3. Size of large elements
    4. None of the above
  5. Private member variables can be accessed directly using
    1. Pointers
    2. Arrays
    3. this pointer
    4. None of the above
  6. The object itself is a
    1. Pointer
    2. Variable
    3. Class member
    4. None of the above
  7. The size of void pointers is
    1. 2 bytes
    2. 0 bytes
    3. 4 bytes
    4. None of the above
  8. The this is present in every
    1. Member function
    2. Non-member function
    3. Every object
    4. All of the above
  9. In the following program, the statement a = &(b = &x);

    void main()

    {

    int x = 10;

    int **a,*b;

    a = &(b = &x);

    cout<<“x = ”<<**a;

    cout<<“ x = ”<<*b;

    }

    1. Address of b is assigned to a
    2. Address of x is assigned to a
    3. Pointer a points to b
    4. Both (a) and (c)

(C) Attempt the following programs

  1. Write a program to declare an integer pointer. Store 10 numbers in the pointer. Use a new operator to allocate memory for 10 integers. Read and display the numbers.
  2. Try the above program without allocating memory. Use an increment operator to get successive locations in the memory. While displaying numbers, retrieve previous memory locations using a decrement operator (Tip: The program without a new operator shows warnings; ignore it for the time being, but in practical application, a new operator is essential.).
  3. Write a program to find the determinant of a 2 × 2 matrix using pointers.

    B(1,1) B(1,2)

    B(2,1) B (2,2)

    The determinant of the matrix is B (1,1)*B (2,2)-B (1,2)*B (2,1).

  4. Write a program to find the number of zero elements in a 3 × 3 matrix. Read and display the elements. Also, write this program using pointers.
  5. Write a program to declare an integer array. Display the contents of the array using pointers.
  6. Write a program using pointers to exchange the values of two float variables.
  7. Write a program to calculate the square and cube of the entered number using pointers.
  8. Write a program to display 10 floating numbers of an array using pointers.
  9. Write a program to accept a string using character pointers and display it.
  10. Write a program using functions and pointers to display an array of 10 integers in reverse order.
  11. Write a program using functions and pointers to perform the addition of two one-dimensional arrays.
  12. Write a program to perform the multiplication of two matrices (3 × 3) using pointers.

(D) Find bugs in the following programs

  1.  

    class set

    { int x; };

    void main()

    {

    set a;

    cout<<endl<<(unsigned)&a.x;

    }

  2.  

    void main()

    {

    int x = 20;

    float *p;

    p = &x;

    cout<<x;

    }

  3.  

    void main()

    {

    void y(int);

    y = 30;

    cout<<y;

    }

  4.  

    void main()

    {

    void *y;

    (int) y = 30;

    cout<<(unsigned)y;

    }

  5.  

    void main()

    {  char *x;

    int u = 10;

    x = &u;

    }

  6.  

    void main()

    {

    int x = 10;

    int *a,*b;

    a=&(b = &x);

    cout<<“x = ”<<*a;

    cout<<“ x = ”<<*b;

    }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset