What is Pointer?
The pointer is a variable storing the memory address of data stored in the computer’s memory. Normally, a variable store numeric, alphanumeric values of the object but pointers stores the memory address of the variable’s values stored in memory.
Assigning and retrieving variable memory address.
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 a 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 the data type of a variable whose memory address is to be assigned to a pointer should be the same as the pointer data type. But void type pointer can handle different types of variables it points to.
To retrieve the 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, an array name is a pointer to its first element.
Eg. arr is an array is 10 elements (int arr;) then arr is a pointer to its first element i.e. arr. To access the values of the array we can also use pointers.
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. The return value of the new operator is a pointer; therefore it should only be assigned to a pointer.
Once the use of the allocated memory is finished we need to deallocate the memory with the delete operator
ReadMore : HashTable in C sharp
Last updated:3/4/2020 3:48:11 AM
Originally published at https://www.mindstick.com on January 1, 2020.