【问题标题】:how to create const int** from int** [duplicate]如何从 int** 创建 const int** [重复]
【发布时间】:2014-03-09 20:51:36
【问题描述】:

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

【问题讨论】:

  • pixelheader 是什么?通常,一个简单的演员表就足够了。
  • pixel是一个int**,用于存储一组像素强度值,header是值之前的东西
  • 那不是const int **pixel2 = pixel;吗?
  • @Kninnug 我仍然遇到同样的错误
  • 你看我说的了吗? “通常情况下,一个简单的演员阵容就足够了。”

标签: c constants double-pointer


【解决方案1】:

如果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

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

【讨论】:

  • 谢谢!没有更多错误
  • 不要用类型转换抑制错误,也不要教别人用类型转换抑制错误。
  • 这本身不是错误
  • @n.m.:那你打算怎么做呢?我使用过需要const T** 的库,而我有T**。如果你知道如何在没有演员的情况下做到这一点,请分享。
  • 那么这是一件坏事吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2014-09-20
  • 2010-11-11
相关资源
最近更新 更多