Pointers
A variable that holds an address value is called a pointer variable or simply pointer.Pointers are hobgoblin of c++ programming.
What are pointers for ? Here some common uses are
· Accessing array elements.
· Passing arguments to a function when the function needs to modify the origonal argument.
· Passing arrays and strings to function.
· Obtaining memory from the system.
· Creating data structures such as linked lists.
Pointers are important feature of c++ programming. But many other languages such as java , visual Basics have no pointers. You can do a lot of programming without pointers but pointers are assentials for c++ programming language.
The idea behind pointers is not complicated.Every byte in computer memory has an address.Addresses are numbers,just as for houses on a street.
The address of operator &:
Address occupied by a variable using the address operator &. Here is a short example that will help you in understanding that topic.
#include <iostream>
using namespace std;
int main ( )
{
int var1 = 10;
int var2 = 20;
cout << &var1<<endl;
cout << &var2<<endl;
return 0;
}
Run this program on your system and machine and then see what the address of var1 and var2 .
Address is not the value of var1 which is 10. Address would be in the form of 6to7 digits.
Address by pointer variables:
By the address we can find where things in memory.
What is the data type of pointer variable ?
A pointer to int ,is not type int .You might think a pointer data type would be called something like pointer or p or ptr.
Example of pointer ( address variables )
#include <iostream>
using namespace std;
int main ( )
{
int var1 = 10;
int var2 = 20;
cout << &var1<<endl;
cout << &var2<<endl;
int *ptr ;
ptr = &var1 ;
cout <<ptr ;
ptr = &var2 ;
cout<< ptr;
return 0;
}
Sample run can be shown when you run this program on your system.
Pointers must have a value:
An address like 0*8ffff4ff can be thought of as a pointer constant.
When we first define a variable , it holds no value. It may hold a garbage value.But in case of pointers , a garbage value is the address of something in memory. So before a pointer is used , a specific address must be placed in it.
ptr = &var;