Wanted to start such posts for a long time. After Abhay posted his queries related to pointers, I decided better late than never. I’ll try to post such stuff more frequent. 🙂
Will always be looking forward for your feedback.
What is a pointer?
Pointer is a variable that stores an address as its value.
How to declare a pointer?
To declare a variable as pointer we have to use “*” along with variable name, in its declaration. Following declaration declares variable i as a pointer to integer.
“*” in the declaration is associated with the variable name, which means in the following declaration while i is a pointer variable, j is of integer.
int* i, j;
The correct way to declare multiple variables as pointers, in same statement, is by adding “*” before each variable name, as shown below.
int *i, *j;
Another way would be to use typedef to create a new type and use that to declare variables of that type.
typedef int * INT_PTR;
INT_PTR i, j;
While it is ok not to initialize a static and global variable, as they are by default initialized to 0 (zero), it is always better to initialize a local variable, to avoid using the garbage value stored in it. Since a pointer stores an address, it becomes more important to make sure we initialize a pointer to a known value, as accessing a random (garbage) address can result in core dump (linux)/segmentation fault (windows).
Now the question is how do we get a valid address to initialize a pointer variable?
One way is to initialize a pointer with the address of a existing variable, as shown below.
int *p = &i; // Initialize pointer p, with address of variable i.
Another way is to dynamically allocate memory and use that address to initialize the pointer variable, as shown below.
int *p = (int *) malloc(sizeof(int));
int *q = new int; // Only for C++ programs.
One more way is, this should be used very carefully, to initialize pointer with a “known” address. This known address might be of some memory reserved by OS and documented. In this case we specify the address as a integer and typecast it to pointer type, before storing it in pointer variable, as shown below. When storing integer into a pointer in the following way one must be very careful in doing so becuase after storing that integer into a pointer, any access of that pointer variable will access the contents of the memory address at the integer location.
int *p = (int *) 0x0417; // Address of a byte where MS-DOS stores status of some keyboard keys.