int const array无法写入

问题描述 投票:1回答:2

编译以下程序

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

导致错误:分配了只读位置'c [0]'。据我了解,const仅适用于c的位置,因此c [0]和c [1]应该是可变的。为什么会产生此错误?

c const
2个回答
4
投票

据我所知,const仅适用于c的位置

没有无论如何,您无法修改阵列的位置。您可能的意思是,如果您有一个int * const,那么那确实是一个指向可修改int的常量指针。但是,int const c[2];是2个常量整数的数组。因此,在声明数组时必须初始化它们:

int const c[2] = {0, 1};

对比之下:

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
}

0
投票

此外,我将补充指出,正确使用const是C程序员最重要的技能之一。它称为const correctness

© www.soinside.com 2019 - 2024. All rights reserved.