C中的常量指针无法更改其指向的变量的地址,即该地址将保持不变。因此,可以说,如果常量指针指向某个变量,则它不能指向任何其他变量。
<type of pointer> *const <name of pointer>;
常量指针的声明如下:
int *const ptr;
让我们通过示例了解常量指针。
#include <stdio.h> int main() { int a=1; int b=2; int *const ptr; ptr=&a; ptr=&b; printf("Value of ptr is :%d",*ptr); return 0; }
在上面的代码中:
输出
在上面的输出中,我们可以看到上面的代码产生错误“assignment of read-only variable 'ptr'"。这意味着不能更改"ptr"持有的变量"ptr"的值。在上面的代码中,我们将'ptr'的值从&a更改为&b,这对于常量指针是不可能的。因此,可以说指向某个变量的常量指针不能指向另一个变量。
指向常量的指针是一种指针,通过该指针不能更改指针所指向的变量的值。这些指针的地址可以更改,但是指针指向的变量的值不能更改。
const <type of pointer>* <name of pointer>
下面给出了指向常量的指针的声明:
const int* ptr;
通过示例让我们理解。
#include <stdio.h> int main() { int a=100; int b=200; const int* ptr; ptr=&a; ptr=&b; printf("Value of ptr is :%u",ptr); return 0; }
在上面的代码中:
输出
上面的代码成功运行,并且在输出中显示了'ptr'的值。
#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; }
在上面的代码中:
输出
上面的代码显示错误"assignment of read-only location * ptr'"。此错误意味着我们无法更改指针指向的变量的值。
指向常量的常量指针是一个指针,它是上述两个指针的组合。它既不能更改其指向的变量的地址,也不能更改该地址处的值。
const <type of pointer>* const <name of the pointer>;
常量的声明如下:
const int* const ptr;
通过示例让我们理解。
#include <stdio.h> int main() { int a=10; int b=90; const int* const ptr=&a; *ptr=12; ptr=&b; printf("Value of ptr is :%d",*ptr); return 0; }
在上面的代码中:
输出
上面的代码显示错误"assignment of read-only location '* ptr'的分配"和"assignment of read-only variable 'ptr'的分配"。因此,我们得出的结论是,指向常量的常量指针不能更改该指针指向的地址或值。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)