Please refer to the introduction to pointers, pointer declarations, and initializations for a better understanding of the below topics:
Constant Pointer:
The constant pointer means that the address is constant that is it cannot be changed but the value to which it is pointing to can be changed.
Syntax:
data_type *const ptr_name;
Example:
The address which is fetched upon doing malloc() should not be lost or changed, hence constant pointers can be used to obtain such address.
Example:
Since the pointer is not const, the address can be changed (to which it is pointing).
#include <stdio.h> int main() { int b = 10; int c = 11; int *ptr = &b; printf ("\n The address is: %x value is: %d", ptr, *ptr); ptr = &c; printf ("\n The address is: %x value is: %d", ptr, *ptr); return 0; } Output: The address is: ccb31044 value is: 10 The address is: ccb31040 value is: 11
Current address cannot be changed:
#include <stdio.h> int main() { int b =10; int c =11; int *const ptr = &b; printf("\n The address is: %x value is: %d", ptr, *ptr); ptr= &c; printf("\n The address is: %x value is: %d", ptr, *ptr); return 0; }
Output:
constant_pointer.c:11:4: error: assignment of read-only variable 'ptr'
ptr= &c
Pointer to constant:
Pointer to constant means the address can be changed but value cannot be changed.
Syntax:
data_type const *ptr_name
or
const data_type *ptr_name
Example:
Passing array or string to a function which should not modify the content of the array or the string.
#include <stdio.h> int main() { int b = 10; int c = 20; int *ptr = &b; printf("\n Address of pointer is: %p\n", ptr); printf ("\n The value of old pointer is: %d\n",*ptr) ptr = &c; printf("\n Address of modified pointer is: %p\n", ptr); *ptr = 30; printf("\n Value of modified is pointer is: %d\n", *ptr); return 0; }
Output:
Address of pointer is: 0x7fff65524244
The value of old pointer is: 10
Address of modified pointer is: 0x7fff65524240
Value of modified is pointer is: 30
Now with pointers to constant:
#include <stdio.h> int main() { int b =10; int c =20; int const *ptr =&b; printf("\n Address of pointer is %p\n", ptr); ptr = &c; printf("\n Address of modified pointer is %p\n", ptr); *ptr = 30; printf("\n Value of modified is pointer is %d\n", *ptr); return 0; }
Output: pointer_constant.c:16:5: error: assignment of read-only location '*ptr' *ptr =30
There is a pointer for which neither the address nor the value can be changed
Syntax:
data_type const *const ptr_name
Void Pointer:
It is a special pointer that can hold the address of any data type. The type of pointer must be known before typecasting accordingly for dereferencing.
Example:
#include <stdio.h> int main() { int a =10; void *b = &a; printf("\n The value is: %d\n", *(int*)b) return 0; }
Output: The value is: 10
The addresses that are returned from malloc(), calloc() and realloc() are void pointers that are later typecasted.
Categories: C Language
Leave a Reply