gpt4 book ai didi

c - 无法写入 int const 数组

转载 作者:行者123 更新时间:2023-12-02 06:46:37 25 4
gpt4 key购买 nike

编译以下程序

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

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

最佳答案

As I understand it, the const only applies to the location of 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
}

关于c - 无法写入 int const 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59718439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com