有没有办法从 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/