Wednesday, August 31, 2011

Reference to a pointer in C++ programs


We can create reference to a pointer also in C++ programs. The declaration of such pointer would look like:

char *pstr=”Hello”;
char *&p=pstr;

In the following C++ program a pointer will hold the base address of a string and another reference to pointer variable will hold the same value. Using the pointer the string will be converted into upper case letters. The same effect will be observed in the reference pointer.

C++ program to demonstrate the use of reference pointer

#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void up(char *p)
{
while(*p!=NULL)
{
*p= toupper(*p);
p++;
}
}
void main()
{
clrscr();
char *pstr;
cout<< "Enter any word:";
cin>>pstr;
char *&p=pstr;
cout<< endl<< "String through the pinter:"<< pstr;
cout<< endl<< "String through the reference pointer:"<< p;
up(pstr);
cout<< endl<< "String through the pinter(after modification):"<< pstr;
cout<< endl<<"String through the reference pointer(after nodification):"<< p;
getch();
}

Though an array of pointers is acceptable in C++ programs>, an array of references is not.


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner