Pointer to const: why is ptr[1] also read-only?

Advertisements

I understand that a pointer to const is a pointer through which the value of the variable that the pointer points cannot be changed. Therefore, in the following example, I expect the compiler to raise an error:

int main()
{
    int a = 42;
    const int *ptr = &a;
    ptr[0]++;

    return 0;
}

Now, why would there also be an error with the following example?

int main()
{
    int a = 42;
    const int *ptr = &a;
    ptr[1]++;

    return 0;
}

This second example (with ptr[1]++) throws error: increment of read-only location ‘*(ptr + 4)’. Therefore it seems that not only the value of the variable that the pointer points cannot be changed, but also the values of other related memory locations cannot be changed either.

What is the exact behaviour regarding this? Where is this behaviour referenced? For example, https://en.cppreference.com/w/c/language/pointer does not seem to be clear about this to me.

>Solution :

The declaration:

const int *ptr;

Specifies that ptr is a pointer to a const int, so you aren’t allowed to change what it points to through that pointer.

The expression ptr + n (recalling that x[y] is the same as *(x + y)) also has type const int *, so you can’t change what that points to either. This is spelled out in sectin 6.5.6p8 of the C standard regarding additive operators:

When an expression that has integer type is added to or subtracted from a pointer, the
result has the type of the pointer operand. …

Leave a ReplyCancel reply