Pointers in C++
Pointer
is a variable in C++ that holds the address of another variable. They
have data type just like variables, for example an integer type
pointer can hold the address of an integer variable and an character type
pointer can hold the address of char variable.
Fig: Pointers in C++ |
Syntax:
data_type
*pointername;
How to declare pointer?
int
*p, var
Program:
#include<iostream.h>
int
main()
{
int
*p,var=101;
p=&var;
cout<<”address
of var:”<<&var<<endl;
cout<<”address
of var:”<<p<<endl;
cout<<”address
of p:”<<&p<<endl;
cout<<”value
of var:”<<*p;
return
0;
}
Output:
Address
of var:0x7fff5dfffc0c
Address
of var:0x7fff5dfffc0c
Address
of p:0x7fff5dfffc10
Value
of var:101
Pointer and arrays
Arrays
is that the array name alone represents the base address of array so while
assigning the address of array to pointer don’t use ampersand sign(&).
p=arr;
Program:
#include<iostream.h>
int
*p;
int
arr[]={1,2,3,4,5,6};
p=arr;
for(int
i=0;i<6;i++)
{
cout<<*p<<endl;
p++;
}
return
0;
}
Output:
1
2
3
4
5
6
No comments:
Post a Comment