A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, a pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however, an integer pointer holds the address of an integer variable. The pointer variable might be belonging to any of the data types such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where * is used to denote that “p” is pointer variable and not a normal variable.
- A Pointer in C is used to allocate memory dynamically i.e. at run time.
- Normal variable stores the value whereas pointer variable stores the address of the variable.
- The content of the C pointer always is a whole number i.e. address.
- Always C pointer is initialized to null, i.e. int *p = null.
- The value of the null pointer is 0.
- & symbol is used to get the address of the variable.
- * symbol is used to get the value of the variable that the pointer is pointing to.
- If a pointer in C is assigned to NULL, it means it is pointing to nothing.
- Two pointers can be subtracted to know how many elements are available between these two pointers.
- But, Pointer addition, multiplication, division are not allowed.
- The size of any pointer is 2 byte (for a 16-bit compiler).
Before we can assign a memory address to a pointer, we need to declare one. Declaring a pointer in C++ is as simple as to declare any other variable with one single difference. Asterix symbol " * " needs to be added and located after the variable type and before a variable name. One rule has to be followed when assigning a memory address to a pointer: pointer type has to match with variable type it will point to. One exception is a pointer to void, which can handle different types of variables it will point to. Assigning a Variable's Memory Address to a Pointer is known as referencing a pointer.
And assigning NULL to a pointer is known as dereferencing is. A pointer must be assigned NULL before the end of the scope of the variable it is referencing to, otherwise, the pointer may start pointing to a memory location that the program does not have access anymore. Such kind of pointers are known as dangling pointer.
No comments:
Post a Comment