Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int const array cannot be written to

Tags:

c

constants

Compiling the following program

int main(void) {
    int const c[2];
    c[0] = 0;
    c[1] = 1;
}

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?

like image 352
pgp Avatar asked Aug 11 '26 21:08

pgp


1 Answers

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};

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
}
like image 174
Blaze Avatar answered Aug 13 '26 10:08

Blaze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!