看一下下面的程序。我不明白的是,为什么我必须将变量的地址强制转换x
为char*
当您想一想它实际上绝对是无用的时候。我真正需要的只是变量的地址,声明语句已经提供了所有必要的类型信息char* ptr
。
#include <stdio.h>
int main(void) {
int x = 0x01020309;
char* ptr = &x; /* The GCC compiler is going to complain here. It will
say the following: "warning: initialization from
incompatible pointer type [enabled by default]". I
need to use the cast operator (char*) to make the
compiler happy. But why? */
/* char* ptr = (char*) &x; */ /* this will make the compiler happy */
printf("%d\n", *ptr); /* Will print 9 on a little-endian machine */
return 0;
}
您是正确的,它没有任何实际差异。出现警告是为了通知您该作业可能有些麻烦。
C具有相当强大的类型检查功能,因此,大多数编译器会在类型不兼容时发出警告。
您可以通过添加显式强制类型来摆脱警告(char*)
,这是在说:
我知道自己在做什么,
char*
即使类型不匹配,我也想将此值分配给指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句