Referncing from
This Thread
Constant Pointers
Lets first understand what a constant pointer is. A constant pointer is a pointer that cannot change the address its holding. In other words, we can say that once a constant pointer points to a variable then it cannot point to any other variable.
A constant pointer is declared as follows :
<type of pointer> * const <name of pointer>
An example declaration would look like :
int * const ptr;
Lets take a small code to illustrate these type of pointers :
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
In the above example :
- We declared two variables var1 and var2
- A constant pointer ‘ptr’ was declared and made to point var1
- Next, ptr is made to point var2.
- Finally, we try to print the value ptr is pointing to.
Pointer to Constant
As evident from the name, a pointer through which one cannot change the value of variable it points is known as a pointer to constant. These type of pointers can change the address they point to but cannot change the value kept at those address.
A pointer to constant is defined as :
const <type of pointer>* <name of pointer>
An example of definition could be :
const int* ptr;
Lets take a small code to illustrate a pointer to a constant :
#include<stdio.h>
int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);
return 0;
}
In the code above :
- We defined a variable var1 with value 0
- we defined a pointer to a constant which points to variable var1
- Now, through this pointer we tried to change the value of var1
- Used printf to print the new value.