const and pointers in C

后端 未结 5 1994
星月不相逢
星月不相逢 2021-02-18 17:47

The use of const with a pointer can make the pointee not modifiable by dereferencing it using the pointer in question. But why neither can I modify what the pointer is not direc

5条回答
  •  悲哀的现实
    2021-02-18 18:12

    The non-modifiability introduced by const depends on where const is written.

    If you write

    const int * ptr = &a;
    

    (or int const * ptr = &a;), the const refers to the pointee, so using the pointer for writing to the destination is forbidden.

    (OTOH, if wou wrote

    int * const ptr = &a;
    

    you couldn't modify ptr.)

    In your case, everything involving writing to the destination is forbidden.

    This includes *ptr and ptr[0] (which are equivalent), but also everything involving a modification of the destination address, such as *(ptr + 2) or ptr[2].

提交回复
热议问题