Home > DeveloperSection > Articles > Pointers

Pointers


C# C# 
Ratings:
0 Comment(s)
 1966  View(s)
Rate this:

Pointers

What is Pointer?

Pointer is a variable storing memory address of data stored in computer’s memory. Normally, a variable stores numeric, alphanumeric values of object but pointers stores the memory address of variable’s values stored in memory.

Assigning and retrieving variable memory address.

Assigning

Before assigning a pointer we need to declare a pointer. To declare a pointer we need to use ‘*’ before a variable name of a pointer (Eg. int *i;). We can declare pointer of any data type as well as self created data types (eg. class). To assign a memory address to a pointer we use ‘&’ sing after the assignment operator (eg. i=&a;).   While assigning a memory address to a pointer we need to keep in mind that data type of a variable whose memory address is to be assigned to a pointer should be same as the pointer data type. But void type pointer can handle different types of variables it points to.

Retrieving

To retrieve value from a pointer we use ‘*’ sign with pointer variable name (eg. cout<<*i;). To print the address pointer pointing to we simply write the pointer variable (eg. cout<<i;).

Pointer and Array

Basically array name is a pointer to its first element.

Eg. arr is a array is 10 elements (int arr[10];) then arr is a pointer to its first element i.e. arr[0]. To access the values of array we can also use pointers.

int *i;

i=arr;

for(int j=0;j<10;j++)

  {

    cout<<*i;

    i++;

  }

In the code above i++ will increment the memory address by one unit according to the allocation size of the data type, here it will increment by 2. And cout<<*i; will display the value stored in the array.

Dynamically Allocating and Deallocating memory

new operator is used to allocate memory dynamically during the runtime. Return value of new operator is pointer; therefore it should only be assigned to a pointer.

Eg.

int *p;

p = new int;

Once the use of the allocated memory is finished we need to deallocate the memory with delete operator

Eg.

delete p;

 

 


Don't want to miss updates? Please click the below button!

Follow MindStick