c - 如何从 int** 创建 const int**

标签 c constants double-pointer

有没有办法从 int** 创建 const int** ?

我目前正在使用:

const int **pixel2=*pixel;

const char **header2=*header;

我不断收到错误:cscd240HW34.c:52:21: warning: initialization from incompatible pointer type [enabled by default] const int **pixel2=*pixel;

最佳答案

如果 pixel 已经是 int ** 类型,则:

const int **pixel2 = (const int **)pixel;

通过解释:需要强制转换的原因是因为这仍然无法为您提供您想象的那么多类型安全性。例如,您现在可以编写:

const int c = 'x';
*pixel2 = &c;    // fine, both are const int *
**pixel = 'y';   // no compiler error, but UB as we modify a non-writable object

所以,看看是否有其他方法可以完成您想做的事情。请注意,pixel2 的定义避免了这种利用

const int * const * pixel2;

尽管遗憾的是,C 仍然需要进行强制转换才能将 pixel 分配给 pixel2

这个问题是 c.l.c 中的 11.10。常见问题解答。

关于c - 如何从 int** 创建 const int**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22288004/

相关文章:

c - Vala 的单元测试框架

c - c 中的循环问题?这里有什么问题?

c++ - C++中的const参数生命周期

PHP未定义常量测试

c - 如何使用双指针从文本文件填充字符串数组?

c - 在单词数组中查找具有特定开头字母的单词

c - 具有默认值的 readline

c++ - 为什么将 "pointer to pointer to non-const"转换为 "pointer to pointer to const"是不合法的

c - 在函数中重新分配后出现段错误