Pointers and Strings:
A string is a sequence of characters. A string type variable is declared in the same manner as an array type variable is declared. This is because a string is an array of character type variables.
Since a string is like an array, pointer variables can also be used to access it. For example:
char st1[ ] = “Pakistan”;
char *st2 = “Pakistan”;
In the above statements, two string variables “st1” & “st2” are declared. The variable “st1” is an array of character type. The variable “st2” is a pointer also of character type. These two variables are equivalent. The difference between string variables ‘st1” & “st2” is that:
- string variable “st1” represents a pointer constant. Since a string is an array of character type, the st1 is the name of the array. Also the name of the array represents its address which is a constant. Therefore st1 represents a pointer constant.
- string variable “st2” represents a pointer variable.
In the following program example, a string is printed by printing its characters one by one.
PROGRAM
#include <iostream.h>
#include <conio.h>
main()
{
char st[1] = “Pakistan”;
void ppp (char*);
clrscr();
ppp(st);
cout<< endl << ”Ok”;
}
void ppp (char *ggs)
{
while (*sss 1= ‘\0’)
{
cout<< *sss <<endl;
*sss++;
}
}
comment closed