【问题标题】:C++ Truncation of constant valueC++ 截断常量值
【发布时间】:2012-11-19 21:39:36
【问题描述】:

我收到了这个警告

warning C4309: 'initializing' : truncation of constant value

当我尝试执行我的 dll 时,它只发送 4 个字节而不是 10 个字节。
有什么问题?

这是我的代码:

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);
}

更新

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);

更新

按照建议,我尝试了 memcpy:

memcpy((char*) buf, storagepkt, sizeof(storagepkt));

更新

unsigned char storagepkt[] = {0x0A, 0x00, 0x01, 0x40, 0x79, 0xEA, 0x60, 0x1D, 0x6B, 0x3E};

修复它。

【问题讨论】:

  • 代码调用pSend(),但没有显示。取而代之的是MySend()。是否有错别字或遗漏了什么?
  • 我在走弯路。两者都被声明了:)
  • @wallyk pSend 正在从内部调用 MySend
  • 哪一行导致了警告信息?你确定 pSend() 真的有效吗?
  • 我认为这只是在抱怨你正在用整数初始化一个 char 数组,但由于它们都适合一个 8 位(无符号)整数,你可以忽略警告

标签: c++ hex


【解决方案1】:

我也可以使用以下代码重现此警告:

const unsigned short cid = 0xdeadfeeb;

这意味着编译器正在截断该值,因为它超出了unsigned short 范围。减小值以解决警告。

【讨论】:

    【解决方案2】:

    我可以使用以下代码重现此警告:

    char aa = 0xff;
    

    警告解决了

    unsigned char aa = 0xff;
    

    (正如 Mark Ransom 已经指出的,我只是添加了一个最小的示例代码来重现警告)

    【讨论】:

      【解决方案3】:

      您正在初始化已签名的char 缓冲区。超过0x7f 的任何内容都超出了它的处理能力,将被转换为负数。实际数据可能没问题,你可以忽略警告,虽然最好是unsigned char

      至于为什么它只发送 4 个字节,这听起来有点像指针的大小。您确定代码与您使用数组而不是传递给函数的指针完全一样吗?即使您将参数声明为数组,函数也不知道数组的大小 - 您需要将数组的大小传递给函数。

      【讨论】:

      • 0xEA (storagepkt[5]) 对于考虑 char 签名的编译器上的 char 来说太大了。
      猜你喜欢
      • 2014-10-24
      • 2011-02-16
      • 2023-04-08
      • 2016-11-11
      • 2013-01-12
      • 2021-02-28
      • 2010-09-23
      • 2021-09-22
      • 1970-01-01
      相关资源
      最近更新 更多