Pointers in C++ programming are used to point the locations in memory. A pointer is a variable whose value is the address of another variable, i.e., the direct address of the memory location.
Pointers are aptly name: they 'point' to locations in memory. A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is: type *var-name; Here, type is the pointer's base type; it must be a valid C++ data type and 'var-name' is the name of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.
Following are the valid pointer declaration:int | *ip; | pointer to an integer |
---|---|---|
double | *dp; | pointer to a double |
float | *fp; | pointer to a float |
char | *ch; | pointer to a character |
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
#include<iostream.h>
#include<conio.h>
void main()
{
int x; //A normal integer.
int *p; //A pointer to an integer, '*p' is an integer, so 'p'
//must be a pointer to an integer.
p = &x; //Read it, 'assign the address of 'x' to 'p'.
cout<<"Enter any character to view address: ";
cin>>x; //Put a value in 'x', we could also use 'p' here.
cout<<"Address is: "<<*p; //Note the use of the '*' to get the value.
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int var = 20; //actual variable declaration.
int *ip; //pointer variable declaration.
ip = &var; //store address of var in pointer variable.
cout<<"Address of var variable: "<<&var<<endl;
//address stored in pointer variable.
cout<<"Address stored in ip variable: "<<ip<<endl;
//access the value using the pointer.
cout<<"Value of *ip variable: "<<*ip<<endl;
getch();
}