[英]Unsigned long into char array
這是我的代碼示例:
/* Standard Linux headers */
/* --------------------------------------------------------------------------
Calculates the CRYPTO
-------------------------------------------------------------------------- */
unsigned long CalculateCRYPTO(
unsigned long ulCount, /* Number of bytes in the data block */
unsigned char *ucBuffer ) /*Data block*/
{
unsigned long ulCRYPTO = 0;
//fonction that i have not coded ...
return( ulCRYPTO );
}
int main (void)
{
/*Variables and socket programming*/
//this is my datablock must be in hexa AA 35 07 (will chnage size and data but for now it's hardcoded)
unsigned char datablock[3];
memset(datablock, '\0' ,sizeof(datablock));
datablock[0]=0xaa;
datablock[1]=0x35;
datablock[2]=0x07;
unsigned long CRYPTO;
CRYPTO=CalculateCRYPTO(sizeof(datablock),datablock); //calculate crypto depending of datablocks
printf("CRYPTO = 0x%08x \n", CRYPTO); //prints me 0xe8ba8fa3 that is what i want
/*Creating the final command*/
//(will chnage size and data but for now it's fixed)
unsigned char cmd_final_hex[7]; //this needs to be DATABLOCKS+CRYPTO
//in hexa AA 35 07 concatenated to inverted CRYPTO so ... A3 8F BA E8 => must be AA 35 07 A3 8F BA E8
memset(cmd_final_hex, '\0' ,sizeof(cmd_final_hex)); //Make sure cmd final is at 0
memcpy(cmd_final_hex, datablock, sizeof(datablock)); //cmd at datablock + 000
// while loop prints me what i want so cmd_final_hex[]=AA 35 07 00 00 ...
//Now i want to concatenate so my idea is to use memcpy and not strcat :
memcpy(&cmd_final_hex[sizeof(datablock)], &CRYPTO, 4);
//and a print gives me AA 35 07 A3 8F BA E8 which is exactly what i want but why do i have to use "&CRYPTO" and not "CRYPTO" in my memcpy. !!!
return 0;
}
我的問題是,為什么最后一個memcpy有效? 我希望把CRYPTO而不是&CRYPTO放在參數中...對我來說,CRYPTO是我想要的值0xe8ba8fa3和&CRYPTO的地址。 對我來說,CRYPTO不是一個指針,為什么我需要使用memcpy和&CRYPTO來使其工作?
順便說一句,我的代碼可能是純粹的災難,我是初學者。 不要猶豫,糾正我!
謝謝 !
我的問題是,為什么最后一個memcpy有效? 我希望把CRYPTO而不是&CRYPTO放在參數中...對我來說,CRYPTO是我想要的值0xe8ba8fa3和&CRYPTO的地址。
你是對的。 CRYPTO
不是指針。 但是, memcpy需要一個指針,所以我們必須給它一個。 我們通過獲取CRYPTO
的地址來做到這一點,這是通過添加&
,因此&CRYPTO
。
memcpy
作用是將內存從一個地址復制到另一個地址(這就是它需要兩個指針的原因),而不管這些地址的實際內容如何。 如果你給它CRYPTO
而不是指向它的指針,它可能會將CRYPTO
的值解釋為一個地址(行為是未定義的,除非編譯器給出一個,否則不能保證會發生什么)。
供參考
memcpy void * memcpy ( void * destination, const void * source, size_t num );
參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.