a pointer acts as a variable which stores the address of another variable of the same datatype. the pointer must be denoted by (*)asterisk symbol. Just as variables pointers are declared before use.
benefits for using pointers:
- pointers can extract addresses of other variables
- pointers allow resizing the dynamically allocated memory block
- pointers can perform dynamic memory allocation and deallocation
- pointers provide an alternate way to access arrays
- pointers can reduce the time of the execution
- pointers provide a way to return a value in multiple ways
- pointers provide direct access to the memory
- complexity and storage for the program reduces, by using pointers
Concept of Pointer:
whenever a variable is declared .the system will allocate a space(location) for the variable in memory. this location have its own address .for example from the below example we declare a variable x (int x=5;)
so. from this example we can asses the value 5 by its variable or using its address(80f).the address are made of numbers and alphabets so they can be assigned to some other variable with an asterisk. the variables that hold memory address are called pointer variables. this value of pointer variables will be stored in another address. Value of pointer the variable will be stored in another memory location.
Declaration of Pointer:
examples: int x; float f;
in the above examples, the first statement carries x as an integer pointer and it tells the compiler, to hold any address of the integer variables.in the second statement f is float pointer, which stores the address of any float variable. here the asterisk mark(*) is known as indirection operator .this also called as deference operator, when a pointer is dereferenced, the value at that address are stored by the pointer is retrieved.
Key points for pointers:
- a pointer is always a whole number because it stores address
- C pointer is initialized to null, i.e. int *x = null.
- the value of the null pointer is 0
- ampersign (&) is used to the address of the variable.
- * symbol is used to get the value of the variable that the pointer is pointing to
- If the pointer is assigned to NULL, it means it is pointing to nothing
- pointers can be subtracted to know the elements between them
- pointers cannot be divided, addition, multiplication is not possible
normal variables provide direct access to their own values but the pointers provide indirect access to the values of the variables whose address it stores. from the above example,the variables a and b and the pointers ptr1 and ptr2 are declared.in the 8th and 9th lines the addresses of the variables are assigned to the pointers .so in 10th line if we printf the pointers without asterisk the output will be addressed .so with asterisk the print output will be the assigned value