Pointers in C++
It is data type which points to another value stored in the memory i.e. it contain address of another variable. It is numerical variable, so need to be declared and initialized before using. Pointer declaration, both type and name need to be specified. The asterisk * specifies a pointer which is address of an item of the specified data type. To specify an integer data type, which is address of an integer, we can declare a pointer p of integer type as int *p or int* p and for of data type string, it can be string *p.
Consider an integer variable x with value 10 assigned to it i.e. int x = 10;. To get the pointer to the data item, address operator & can be used. To declare a pointer, for memory address of x, we can declare as int p* = & x ;. While printing *p will print the vaue stored at address x i.e. 10, so cout>>p*<<endl; will print the value 10. Here * is dereference operator and & is address operator. Any number of pointers can point to the same address.
Pointers is one of the most powerful feature of C and C++ languages. They are key to achieve Dynamic Memory Allocation. Dynamic Memory is used to allocate memory without defining variables by using pointers point to them. Pointers help in creation and efficient manipulation of dynamic data structures such as Structures, Linked Lists, Stacks, Queues, Stacks, Trees, Graphs etc. Pointers can be very helpful to optimize algorithms requiring frequent access to large amounts of data.
With all their advantages, use of Pointers demand some precautions. If not used correctly such as writing an incorrect pointer to write a memory location, can lead to very undesirable consequences for the program. Debugging wrong use of pointers can be challenging!