【问题标题】:Why can't I modify a variable through a const pointer? [duplicate]为什么我不能通过 const 指针修改变量? [复制]
【发布时间】:2016-05-25 06:50:18
【问题描述】:

看看这段代码:

int main() {
    int foo = 0;
    const int *ptr = &foo;
    *ptr = 1; // <-- Error here
    return 0;
}

编译时,clang给我一个错误:

const.c:5:7: error: read-only variable is not assignable

是的,ptr 是 const,但 foo 不是。为什么我不能为foo 赋值?

【问题讨论】:

  • ptr 不是const*ptr 是。
  • int* const ptr = &amp;foo; 试试这个。
  • @jrok 这如我所愿,谢谢:)

标签: c++ c pointers constants


【解决方案1】:

你需要区分这些:

const int *ptr = &foo; // <-- NON-CONST pointer, CONST data.
                       // ptr _can_ point somewhere else, but what it points to _cannot_ be modified.


int * const ptr = &foo; // <-- CONST pointer, NON-CONST data.
                        // ptr _cannot_ point to anywhere else, but what it points to _can_ be modified.

const int * const ptr = &foo; // <-- CONST pointer, CONST data.
                              // ptr _cannot_ point to anywhere else, and what it points to _cannot_ be modified.

【讨论】:

    【解决方案2】:

    const int * 是一个指向整数常量的指针

    这意味着,它指向的整数值不能使用该指针更改。即使存储值的内存 (foo) 被声明为普通变量而不是 const,但您用来更改值的变量是 指向整数常量的指针

    现在,您可以使用 foo 更改值,但不能使用该指针。


    指向整数常量的指针指向整数的常量指针是有区别的。

    指向整数的常量指针定义为int * const。初始化后,您不能使指针指向其他内存。

    指向整数常量的指针定义为int const *const int *。不能通过这个指针本身改变指针所指向的值。


    注意: 使用main()的标准定义

    int main(void) //if no command line arguments.
    

    【讨论】:

    • 所以const int * ptrint * restrict ptr 相同?
    • 不,restrict 完全不同。这是一种告诉编译器内存不会被任何其他指针或变量访问的方法。见this
    • @sunqingyao:完全没有,restrict 有完全不同的含义。这是程序员的承诺,ptr 访问的任何内容在其范围内都不会被另一个 restrict 限定指针访问或修改。这是启用积极编译器优化的高级功能,您可以在此阶段完全忽略它。
    • @sunqingyao:当您将const type * 指针分配给不合格的type *void * 指针时,编译器会发出const丢弃 的诊断信息使用赋值运算符= 或通过将const 指针作为没有const 声明的参数传递。这表明了一种危险的情况,即当在承诺不会被修改的情况下接收到数据时,可能会通过分配的指针对其进行修改。如果数据本身是const,它会调用未定义的行为。始终const 限定不用于修改数据的指针。
    • @CoolGuy: 在 C99 中是:第一个 const int const * const a 在同一个对象上有 2 个 const 限定符,但可以按照 C11 6.7.3p5 中的规定:如果相同的限定符直接或通过一个或多个 typedef 在同一个说明符限定符列表中出现多次,行为与只出现一次相同。请注意,这是 C99 与 C90 中的一个更改,它是违反约束的:同一类型限定符不得直接或通过一个或多个 typedef 出现在同一说明符列表或限定符列表中多次。
    猜你喜欢
    • 1970-01-01
    • 2019-12-06
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多