简体   繁体   English

来自不兼容指针类型的分配

[英]Assignment from incompatible pointer type

I'm not sure why this is happening, I think I'm doing everything correctly.. Maybe someone can help point me in the right direction. 我不确定为什么会这样,我认为我做的一切都正确。。也许有人可以帮我指出正确的方向。

    unsigned short* x;

    int textLeft[16];

    x = shm->textLeft;

These are spaced out in the program so I didn't want to copy a bunch of code but if more is needed please let me know. 这些在程序中间隔开了,所以我不想复制一堆代码,但是如果需要更多代码,请告诉我。

Shouldn't this work correctly without giving me the incompatible pointer type? 如果不给我不兼容的指针类型,就不能正常工作吗?

No, this should not work, because you're assigning an int* value to an unsigned short* variable, which causes undefined behavior per the C strict aliasing rule . 不,这不应该工作,因为您正在将int*值分配给unsigned short*变量,这会导致按照C 严格的别名规则导致未定义的行为。

The way to make this work without changing the types is to 无需更改类型即可进行此工作的方法是

  1. cast the pointer, x = (unsigned short *)(shm->textLeft); x = (unsigned short *)(shm->textLeft);指针, x = (unsigned short *)(shm->textLeft); , and
  2. compile with GCC's -fno-strict-aliasing to turn the aliasing rule off. 使用GCC的-fno-strict-aliasing进行编译以关闭别名规则。

But really, I strongly recommend you change the types to be compatible, since otherwise you're tying yourself to a single compiler's extensions to the C standard. 但是实际上,我强烈建议您更改类型以使其兼容,因为否则,您将自己绑定到单个编译器对C标准的扩展。

`unsigned short`

is not 不是

`int`

So define 所以定义

  • x as int * or xint *
  • textLeft[16] as unsigned short textLeft[16]unsigned short

and things are ok. 一切都很好。

In your case x is a unsigned short pointer and textLeft is a signed integer. 在您的情况下, x是无符号的短指针,而textLeft是有符号的整数。 You are trying to assign signed integer address to unsigned short pointer. 您试图将带符号的整数地址分配给无符号的短指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM