A constant pointer in C cannot change the address of the variable to which it is pointing, i.e., the address will remain constant. Therefore, we can say that if a constant pointer is pointing to some variable, then it cannot point to any other variable.
Syntax of Constant Pointer
int main()
{
int a=1;
int b=2;
int *const ptr;
ptr=&a;
ptr=&b;
printf("Value of ptr is :%d",*ptr);
return 0;
}
In the above code:
- We declare two variables, i.e., a and b with values 1 and 2, respectively.
- We declare a constant pointer.
- First, we assign the address of variable 'a' to the pointer 'ptr'.
- Then, we assign the address of variable 'b' to the pointer 'ptr'.
- Lastly, we try to print the value of the variable pointed by the 'ptr'.
Output
Pointer to Constant
A pointer to constant is a pointer through which the value of the variable that the pointer points cannot be changed. The address of these pointers can be changed, but the value of the variable that the pointer points cannot be changed.
Let's understand through an example.
- First, we write the code where we are changing the value of a pointer
int main()
{
int a=100;
int b=200;
const int* ptr;
ptr=&a;
ptr=&b;
printf("Value of ptr is :%u",ptr);
return 0;
}
In the above code:
- We declare two variables, i.e., a and b with the values 100 and 200 respectively.
- We declare a pointer to constant.
- First, we assign the address of variable 'a' to the pointer 'ptr'.
- Then, we assign the address of variable 'b' to the pointer 'ptr'.
- Lastly, we try to print the value of 'ptr'.
Output
The above code runs successfully, and it shows the value of 'ptr' in the output.
- Now, we write the code in which we are changing the value of the variable to which the pointer points.
#include <stdio.h>
int main()
{
int a=100;
int b=200;
const int* ptr;
ptr=&b;
*ptr=300;
printf("Value of ptr is :%d",*ptr);
return 0;
}
In the above code:
- We declare two variables, i.e., 'a' and 'b' with the values 100 and 200 respectively.
- We declare a pointer to constant.
- We assign the address of the variable 'b' to the pointer 'ptr'.
- Then, we try to modify the value of the variable 'b' through the pointer 'ptr'.
- Lastly, we try to print the value of the variable which is pointed by the pointer 'ptr'.
Output
No comments:
Post a Comment