[英]warning: incompatible pointer types [-Wincompatible-pointer-types] in C
Why do I get a warning here?为什么我会在这里收到警告? How can I fix this?我怎样才能解决这个问题?
memUnit * newUnit = (char*) freeUnit + sizeof(memUnit);
I want to allocate a new Unit after the old Unit in my Memory (basically DIY calloc()).我想在我的 Memory (基本上是 DIY calloc())中的旧单元之后分配一个新单元。 All variables with the word Unit in it are all of the struct memUnit.所有带有Unit这个词的变量都是struct memUnit。
Everything works fine like this, but how do I fix the warning?一切都像这样正常工作,但我该如何解决警告?
You're trying to assign a char *
into a memUnit *
.您正在尝试将char *
分配给memUnit *
。
Now, I don't know what memUnit
is in this context, but if it's larger than a single-byte value, you're assigning a byte-aligned pointer into a (something larger)-aligned pointer, and the compiler has every reason to complain.现在,我不知道memUnit
在这种情况下是什么,但是如果它大于单字节值,那么您将字节对齐的指针分配给(更大的)对齐的指针,编译器有充分的理由抱怨。 I'm assuming that's the problem.我假设这就是问题所在。
If freeUnit
is declared as memUnit *
, you don't need to cast the pointer type.如果freeUnit
被声明为memUnit *
,则不需要转换指针类型。 Just use:只需使用:
memUnit *newUnit = freeUnit + 1;
or memUnit *newUnit = &freeUnit[1];
或memUnit *newUnit = &freeUnit[1];
If freeUnit
is some other type, particularly one with a different size/alignment, you're on dangerous ground如果freeUnit
是其他类型,尤其是具有不同大小/对齐方式的类型,那么您将处于危险之中
If it's a type with the exact same size as memUnit
, and you have checked it's correctly aligned, you could cast it to memUnit *
and add one, as above.如果它是与memUnit
大小完全相同的类型,并且您已检查它是否正确对齐,则可以将其强制转换为memUnit *
并添加一个,如上所述。
There is no implicit conversion from a pointer to the type char * to any other pointer to object type except the type void *.没有从指向 char * 类型的指针到指向 object 类型的任何其他指针的隐式转换,除了类型 void *。
So you need to write either所以你需要写
memUnit * newUnit = ( memUnit * )( (char*) freeUnit + sizeof(memUnit) );
or或者
memUnit * newUnit = ( void * )( (char*) freeUnit + sizeof(memUnit) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.