GCC 指针转换警告
我想知道为什么 GCC 给我这个警告:
test.h: In function TestRegister:
test.h:12577: warning: cast to pointer from integer of different size
代码:
#define Address 0x1234
int TestRegister(unsigned int BaseAddress)
{
unsigned int RegisterValue = 0;
RegisterValue = *((unsigned int *)(BaseAddress + Address)) ;
if((RegisterValue & 0xffffffff) != (0x0 << 0))
{
return(0);
}
else
{
return(1);
}
}
I am wondering why GCC is giving me this warning:
test.h: In function TestRegister:
test.h:12577: warning: cast to pointer from integer of different size
Code:
#define Address 0x1234
int TestRegister(unsigned int BaseAddress)
{
unsigned int RegisterValue = 0;
RegisterValue = *((unsigned int *)(BaseAddress + Address)) ;
if((RegisterValue & 0xffffffff) != (0x0 << 0))
{
return(0);
}
else
{
return(1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能是因为您使用的是 64 位平台,其中指针是 64 位,但
int
是 32 位。经验法则:不要尝试使用整数来存储地址。
Probably because you're on a 64-bit platform, where pointers are 64-bit but
int
s are 32-bit.Rule-of-thumb: Don't try to use integers to store addresses.
如果包含
并且编译 对于 C99 标准,使用gcc -Wall -std=c99
您可以进行转换intptr_t
这是一个与指针大小相同的整数类型。If you include
<stdint.h>
and if you compile for the C99 standard usinggcc -Wall -std=c99
you could cast to and fromintptr_t
which is an integer type of the same size as pointers.除此之外,您假设指针适合到
unsigned int
,而C没有提供这样的保证......有一个数字今天使用的平台中有很多这是不真实的,显然包括您的平台。指向数据的指针可以安全地存储在
(void*)
或 (type*
) 中。可以将指针添加到(或减去)size_t
或ssize_t
。sizeof(int)
、sizeof(size_t)
、sizeof(ssize_t)
和(void*)< 之间不存在保证关系/code> 或 (type
*
)...(此外,在这种情况下,初始化 var 并在下一行覆盖它没有实际意义...)
也无关,但您意识到
!= (0x0 << 0)
→!= 0
并且可以省略,因为if (x)
=if (x != 0 )
...?也许这是因为这是从更大的样本中截取的,但是整个例程可以表示为(编辑:更改为
unsigned int*
因为他似乎更有可能想跳过int
大小的偏移量?)Among other things, you're assuming that a pointer will fit into an
unsigned int
, where C gives no such guarantee… there are a number of platforms in use today where this is untrue, apparently including yours.A pointer to data can be stored in a
(void*)
or (type*
) safely. Pointers can be added to (or subtracted to yield) asize_t
orssize_t
. There's no guaranteed relationship betweensizeof(int)
,sizeof(size_t)
,sizeof(ssize_t)
, and(void*)
or (type*
)…(Also, in this case, there's no real point in initializing the var and overwriting it on the next line…)
Also unrelated, but you realise that
!= (0x0 << 0)
→!= 0
and can be omitted, sinceif (x)
=if (x != 0)
… ? Perhaps that's because this is cut down from a larger sample, but that entire routine could be presented as(Edited: changed to
unsigned int*
as it seems far more likely he wants to skip through atint
-sized offsets?)