Practical C++ Part 9 : Pointers
By Rae
This part of the "Practical C++" series deals with probably the most confusing aspect of C/C++ programming, that is, pointers. Pointers are variables that point to an area in memory. They do not contain actual data, but point to memory locations which hold the data.
To define a pointer, you just have to prefix an asterisk (*) before the variable name, for example,
int *ptr;
This will define a pointer 'ptr' which will hold the address of a memory location holding an integer number. Now suppose we have a integer number say 'num'. To make the pointer 'ptr' point to 'num', we have to write the following statement :-
ptr = #
The ampersand (&) sign should be read as 'the address of', and causes the address in memory of a variable to be returned, instead of the variable itself. Therefore now, 'ptr' starts pointing to the memory location of 'num'. The asterisk (*) should be read as 'the value pointed by'. So if, you directly want to change the value of 'num', you can do so with the help of the pointer 'ptr'. Just write,
*ptr = 8;
To get all these concepts clearer, we will now write the complete code :-
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int num;
int *ptr;
num = 5;
ptr = #
cout<<"The value is : "<<num<<endl;
*ptr = 8;
cout<<"The new value is : "<<num<<endl;
getch();
}
The output of the above code will be :-
The value is : 5
The new value is : 8
For the advanced programmer, a conceptual understanding of pointers is absolutely essential. They form the basis of resizeable arrays, dynamic memory allocation concepts and all of data strucutres including linked lists, stacks and queues. To allocate memory dynamically in you program, use the follwing lines of code :-
int *ptr;
ptr = new int;
The keyword 'new' is used to initialize pointers with memory from free store. Thus 'ptr' now points to its own exclusive memory location, of the size of an 'int' data type. And at the end of the program, or whenever required, we must free up the memory we have allocated using 'new'. This is done using the keyword 'delete', as shown,
delete ptr;
Now at this point we have to be very careful about freeing the memory space. Always pass a valid pointer to 'delete', otherwise it may lead undesirable circumstances like crashing.
References :-
http://www.codeguru.com
Understanding Pointers in C by Yashvant Kanetkar
C++ : The Complete Reference by Herbert Schildt
Written by Rae
Written by rae
Edited by NeorageX |