Tag: readonly

const指针修复变量变量

我无法弄清楚如何告诉C我想要一个不会移动的指针。 它总是指向同一个数组。 也就是说,数组成员不是常量,但数组本身是全局的,因此,它处于固定位置。 所以,当我编码时: #include int v[2]={0, 1}; const int *cpv=v; int main(void) { v[1]=2; printf(“%d\n”, v[1]); *(cpv+1)=3; printf(“%d\n”, v[1]); cpv[1]=4; printf(“%d\n”, v[1]); } 并得到这个错误: constp.c: In function ‘main’: constp.c:9: error: assignment of read-only location ‘*(cpv + 4u)’ constp.c:10: error: assignment of read-only location ‘*(cpv + 4u)’ 我知道编译器认为我需要一个const int v[2]来使用const int *iv 。 如何获得一个常量指针来完成这项工作? 如果你看到错误信息,我甚至没有移动指针(如pv++ […]

使C模块变量可以只读方式访问

我想为模块变量提供客户端模块的只读访问权限。 几种解决方案 1 。 最常见的一个: // module_a.c static int a; int get_a(void) { return a; } // module_a.h int get_a(void); 这使得每个变量共享一个函数,一个函数调用(我正在考虑执行时间和可读性),每个读取一个副本。 假设没有优化链接器。 2 。 另一种方案: // module_a.c static int _a; const int * const a = &_a; // module_a.h extern const int * const a; // client_module.c int read_variable = *a; *a = 5; // […]