C++ tutorial-C++ Pointer


C++ Pointer

What is a pointer?

A pointer is a variable that holds a memory address and points to the value at the address.

Declaring and using pointers

To declare a pointer, you must write down the data type of the pointer and * in front of the name of the pointer.
float *i;
To hold a memory address of another variable, you will use & operator.
Example:
float x;
float *i;
i = &x;
You will use the * operator to dereference a pointer.
Example:

float x;
float *i;
i = &x;
*i=10;//assign a value to x variable using pointer i
cout<<x;

Operations on a pointer

You can also perform operations on a pointer by using the arithmetic operators such as +, -, *, and /.
Example:
int *p;
int x=20;
p=&x;
cout<<(*p)+10; //add 10 to the value of x variable
cout<<p+1;//add 1 to the address of x variable

A Pointer to an array

A pointer can be used to point an array. The pointer will point to the address of the first element of the array. If you don't know the array please read this page: C++ Array.
Example:
float *p;
float data[]={12,34,45,56,34};
p=data;
cout<<*p;
To point to the subsequent elements of the array you need to increase the address that the pointer points to by one.
Example:
for(int i=0;i<5;i++)
  cout<<*(p+i); 

An array of pointers

You can create an array to store a collection of pointers. This is called the array of pointers.
Example:
int *values[5];
int x=100;
values[0]=&x;
cout<<*values[0];


Comments

Troy comment

 Troy

for more C++, C exercises,
please visit http://ccphplusplus.blogspot.com/


2015-05-26
Dara comment

 Dara

Let pointer p point to the index 1 elem (value=2) of the array.
int *p= a+1;
Let pointer q point to the index 6 elem (value=5) of the array.
int *q= a+6;
-Expression q-p is the subtraction of address of the index 6 element and the address of index 1 elem of the array. So, the result is 5.
-Expression *p+*q is the sum of the value of index 1 elem (2) and the value of index 6 elem (5). So, the result is 7.
In conclusion, the output is 57.


2013-03-28
Anushka  comment

 Anushka

Find the output of following code
main()
{
int a[] = {1,2,9,8,6,3,5,7,8,9};
int *p= a+1; int *q= a+6;
cout<< q-p <<*p+*q; }


2013-03-28



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.