[c语言] const常量总结

指向常量的指针

不能通过指针修改它所引用的值,但指针所指向的对象

int main(void)
{
    int num = 10;
    int num1 = 20;
    const int *p;

    p = #
    printf("%d\n", *p);
    p = &num1;
    printf("%d\n", *p);

    *p = 30;
    printf("%d\n", *p);     //error: assignment of read-only location '*p'

    return 0;
}
  • p可以修改为指向不同的整数常量
  • p可以修改为指向不同的非整数常量
  • 可以解引p以读取数据
  • 不能解引p从而修改它指向的数据

指向非常量的常量指针

这意味着指针不可改变,但它指向的值可以改变

int main(void)
{
    int num = 10;
    int num1 = 20;
    int *const p = #

    printf("%d\n", *p);
    *p = 30;
    printf("%d\n", num);

    p = &num1;      //error: assignment of read-only variable 'p'

    return 0;
}
  • p必须被初始化为指向非常量指针,否则warning: initialization discards 'const' qualifier from pointer target type
  • p不能被修改
  • p指向的数据可以修改

指向常量的常量指针

这种指针很少派上用场。指针本身不能被修改,它指向的数据也不能通过它来修改

Good Good Study! Day Day Up!

原文地址:https://www.cnblogs.com/kdurant/p/4216895.html