2012-12-02 48 views
5

的C++截斷我得到這個警告恆定值

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

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

件作爲建議我嘗試過的memcpy:

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

UPDATE

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

固定它。

+0

該代碼調用'pSend()',但沒有出現。而是'MySend()'。是否有錯字或缺失? – wallyk

+0

我正在使用彎路。都宣佈:) – madziikoy

+0

@wallyk'pSend'正在從'MySend'裏面調用 –

回答

15

您正在初始化已簽名的char的緩衝區。超過0x7f的任何內容都超出了它所能處理的範圍,並將轉換爲負數。實際的數據可能是確定的,你可以忽略這個警告,儘管最好使它成爲unsigned char

至於爲什麼它只發送4個字節,這聽起來像一個指針的大小。你確定代碼和你代表的一樣,使用數組而不是傳遞給函數的指針嗎?即使將參數聲明爲數組,函數也不知道數組的大小 - 您需要將數組的大小傳遞給函數。

+0

0xEA(storagepkt [5])對於考慮char簽名的編譯器中的字符太大。 –

5

我可以重現這個警告,用下面的代碼:

char aa = 0xff; 

警告的解決,是

unsigned char aa = 0xff; 

(馬克贖金已經指出的那樣,我只是增加了一個最小的示例代碼重現警告)

0

我也可以用下面的代碼重現此警告:

const unsigned short cid = 0xdeadfeeb; 

這意味着該值正在被編譯器截斷,因爲它不在unsigned short範圍內。降低值以解決警告。