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.
float x;
float *i;
i = &x;
You will use the * operator to dereference a pointer.

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

Operations on a pointer

You can also perform operations on a pointer by using the arithmetic operators such as +, -, *, and /.
int *p;
int x=20;
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.
float *p;
float data[]={12,34,45,56,34};
To point to the subsequent elements of the array you need to increase the address that the pointer points to by one.
for(int i=0;i<5;i++)

An array of pointers

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


Troy comment


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

Dara comment


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.

Anushka  comment


Find the output of following code
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; }


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.