int const array cannot be written to

pgp*_*pgp 2 c constants

Compiling the following program

int main(void) {
    int const c[2];
    c[0] = 0;
    c[1] = 1;
}
Run Code Online (Sandbox Code Playgroud)

leads to error: assignment of read-only location ‘c[0]’. As I understand it, the const only applies to the location of c and so c[0] and c[1] should be mutable. Why is this error produced?

Bla*_*aze 8

As I understand it, the const only applies to the location of c

No. You can't modify the location of the array anyway. What you probably mean is if you have a int * const, then that indeed is a constant pointer to a modifiable int. However, int const c[2]; is an array of 2 constant ints. As such, you have to initialize them when you declare the array:

int const c[2] = {0, 1};
Run Code Online (Sandbox Code Playgroud)

In constrast:

int main(void) {
    int c[2];
    int* const foo = c;
    foo[0] = 0;
    foo[0] = 1;
    //foo = malloc(sizeof(int)); doesn't work, can't modify foo, as it's constant
}
Run Code Online (Sandbox Code Playgroud)

  • @AndreasWenzel `const int` 和 `int const` 是等价的 - 后者是奇怪的风格。然而,“const int*”和“int * const”的含义不同。 (6认同)