C++ 截断常量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13666033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Truncation of constant value
提问by madziikoy
I'm getting this warning
我收到此警告
warning C4309: 'initializing' : truncation of constant value
and when I try to execute my dll it only sends 4 bytes instead of the 10 bytes.
What could be wrong?
当我尝试执行我的 dll 时,它只发送 4 个字节而不是 10 个字节。
可能有什么问题?
Here is my code:
这是我的代码:
int WINAPI MySend(SOCKET s, const char* buf, int len, int flags)
{
cout << "[SEND:" << len << "] ";
for ( int i = 0; i < len; i++ ) {
printf( "%02x ", static_cast<unsigned char>( buf[i] ) );
}
printf("\n");
//causing the warning:
char storagepkt[] = {0x0A, 0x00, 0x01, 0x40, 0x79, 0xEA, 0x60, 0x1D, 0x6B, 0x3E};
buf = storagepkt;
len = sizeof(storagepkt);
return pSend(s, buf, len, flags);
}
UPDATE
更新
int (WINAPI *pSend)(SOCKET s, const char* buf, int len, int flags) = send;
int WINAPI MySend(SOCKET s, const char* buf, int len, int flags);
UPDATE
更新
As suggested I tried memcpy:
按照建议,我尝试了 memcpy:
memcpy((char*) buf, storagepkt, sizeof(storagepkt));
UPDATE
更新
unsigned char storagepkt[] = {0x0A, 0x00, 0x01, 0x40, 0x79, 0xEA, 0x60, 0x1D, 0x6B, 0x3E};
Fixed it.
修复。
回答by Mark Ransom
You're initializing a buffer of char
which is signed. Anything over 0x7f
is beyond what it can handle and will be converted to a negative number. The actual data is probably OK and you can ignore the warning, although it would be better to make it unsigned char
.
您正在初始化一个char
已签名的缓冲区。任何0x7f
超出的范围都超出了它的处理能力,将被转换为负数。实际数据可能没问题,您可以忽略警告,尽管最好将其设为unsigned char
。
As for why it's only sending 4 bytes, that sounds suspiciously like the size of a pointer. Are you sure the code is exactly as you've represented it, using an array, rather than a pointer passed to a function? A function doesn't know the size of an array even when you declare the parameter as an array - you need to pass the size of the array into the function.
至于为什么它只发送 4 个字节,这听起来很像一个指针的大小。您确定代码与您表示的完全一样,使用的是数组,而不是传递给函数的指针吗?即使将参数声明为数组,函数也不知道数组的大小 - 您需要将数组的大小传递给函数。
回答by Zac
I can reproduce this warning with the following code:
我可以使用以下代码重现此警告:
char aa = 0xff;
the warning is solved with
警告解决了
unsigned char aa = 0xff;
(as Mark Ransom already pointed out, I just added a minimal sample code to reproduce the warning)
(正如 Mark Ransom 已经指出的,我只是添加了一个最小的示例代码来重现警告)
回答by Croll
I also can reproduce this warning with following code:
我还可以使用以下代码重现此警告:
const unsigned short cid = 0xdeadfeeb;
Which means that value is being truncated by compiler, because it is out of unsigned short
range. Decrease value to solve warning.
这意味着该值被编译器截断,因为它超出了unsigned short
范围。减小值以解决警告。